lior r lior r - 5 months ago 9
Javascript Question

Javsacript object reference from jquery callback

Say that i have this code

var SomeClass= function(id){
this.id = guidGenerator();
this.htmlElement = jQuery("#"+id);
this.initClickHandler();
};

SomeClass.prototype = {
initClickHandler: function(){
this.htmlElement.on("click",function(e){
//NEED A REFERENCE TO THE OBJECT HERE
//IN A WAY THAT WILL ALLOW SOMETHING LIKE THIS
//this.clickHandler();
});
},
clickHandler: function(){
alert(this.id);
}
};

SomeClassInstance1 = new SomeClass("a");
SomeClassInstance2 = new SomeClass("b");


how can i get the relevant instance of "SomeClass" on the "ON "callback ?

Answer

Need a reference to the object here in a way that will allow something like this

Use a variable to keep a reference to this:

SomeClass.prototype = {
  initClickHandler: function() {
    var me = this;
    this.htmlElement.on("click", function(e) {
      me.clickHandler();
    });
  },
  clickHandler: function() {
    alert(this.id);
  }
};

In your case you can also bind the context wbith: fun.bind(thisArg[, arg1[, arg2[, ...]]]):

this.htmlElement.on("click", this.clickHandler.bind(this));

Also note that it's recommended to start instances with lowercase:

var someClassInstance1 = new SomeClass("a");
var someClassInstance2 = new SomeClass("b"); 
Comments