0

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 ?

lior r
  • 2,020
  • 6
  • 38
  • 78

1 Answers1

0

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"); 
andlrc
  • 41,466
  • 13
  • 82
  • 108
  • 1
    @liorr I would recommend you read the post that I marked as a duplicate. It have a lot of good information :-) – andlrc Jun 11 '16 at 11:46