javascript - Javsacript object reference from jquery callback -


this question has answer here:

say have 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 reference object here                //in way allow                //this.clickhandler();           });       },       clickhandler: function(){           alert(this.id);       }  };  someclassinstance1 = new someclass("a"); someclassinstance2 = new someclass("b"); 

how can relevant instance of "someclass" on "on "callback ?

need reference object here in way allow this

use variable keep reference this:

someclass.prototype = {   initclickhandler: function() {     var me = this;     this.htmlelement.on("click", function(e) {       me.clickhandler();     });   },   clickhandler: function() {     alert(this.id);   } }; 

in case can bind context wbith: fun.bind(thisarg[, arg1[, arg2[, ...]]]):

this.htmlelement.on("click", this.clickhandler.bind(this)); 

also note it's recommended start instances lowercase:

var someclassinstance1 = new someclass("a"); var someclassinstance2 = new someclass("b");  

Comments

Popular posts from this blog

Export Excel workseet into txt file using vba - (text and numbers with formulas) -

wordpress - (T_ENDFOREACH) php error -

Using django-mptt to get only the categories that have items -