I’m creating a control for Google maps v2. While creating my control I’ve found a design challenge and want to find an appropriate solution. Here’s the goods.
A custom Google control inherits from GControl;
myControl.prototype = new GControl();
Next I need to overload the initializer so here it is.
myControl.prototype.initilize = function (map) {
//do some work and return stuff
};
Now within my custom controls initlize function I create a couple elements which, using the GEvent class, I subscribe to various events. To make my callback functions managable, I included them into the controls prototype.
myControl.prototype.onEvent = function(e){
//do some work;
//modify the members of the current myControl instance
};
Within my callback function “onEvent” I want to modify members within my control. What is the best way to access my control from the function? The keyword “this” cannot be used because that is a reference to the element that was clicked, in my case a div. And I can’t access the members through the prototype because I need a specific instance of the object. The only viable solution I’ve considered is to create my control globally in one of my scripts. Is this the best method?
The easiest thing that I can think, it to define your
onEventmethod within your constructor, there you will have quick access to the current object instance, and you will not have to modify your public API:Note that in this approach, the
onEventproperty will exist physically in your object instances (obj.hasOwnProperty('onEvent') = true).Edit: You can simply use the
GEvent.bindfunction:The above
bindmethod will enforce the context, so thethiskeyword insidemyObj.onEventwill point to themyObjobject instance when the event is triggered, it will work with your code without problems.