views:

35

answers:

2

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?

A: 

I'm not familiar with how you subscribe to events using GEvent, so I'll make that part up. Do this:

myControl.prototype.onEvent = function(e, instance) {
  // do some work
  // modify members of 'instance'
};

function wrap(handler, instance) {
  return function(e) {
    handler(e, instance);
  }
}

GEvent.Register('Event', wrap(instance.onEvent, instance));
Bruce
+1  A: 

The easiest thing that I can think, it to define your onEvent method within your constructor, there you will have quick access to the current object instance, and you will not have to modify your public API:

function MyControl () {
  var instance = this; // store a reference to 'this'

  this.onEvent = function (e) {
    // use the instance variable
    instance.otherMethod();
  };
}

Note that in this approach, the onEvent property will exist physically in your object instances (obj.hasOwnProperty('onEvent') = true).

Edit: You can simply use the GEvent.bind function:

GEvent.bind(map, "click", myObj, myObj.onEvent);

The above bind method will enforce the context, so the this keyword inside myObj.onEvent will point to the myObj object instance when the event is triggered, it will work with your code without problems.

CMS
I like that way too, if he doesn't mind not using the prototype.
Bruce
Bind works great. Thank you!
Matt