javascript - How to reference object instance from event handler -


in code below, there better way reference object instance handleclick() pulling in global?

var widget = function() {   this.property = 'value';   this.bindevents(); }  widget.prototype = {    bindevents: function() {     $('button').on('click', this.handleclick);   },    handleclick: function() {     var self = window.widget;      console.log(self.property);   } }  window.widget = new widget(); 

this question asks same thing, , (non-accepted) answer pass callback $.on() , call handler there, passing in instance parameter this:

bindevents: function() {   var self = this;    $('button').on('click', function() {     self.handleclick.apply(self);   }); } 

is technique of passing instance around right way it, or there still preferred way besides 2 i've shown?

you use bind():

bindevents: function() {   $('button').on('click', function() {     this.handleclick();   }.bind(this));  } 

but when comes ie, work in ie >= 9.

edit: in legacy ie, use, suggested @kevin b in comment, jquery's $.proxy():

bindevents: function() {   $('button').on('click', $.proxy(function() {     this.handleclick();   }, this));  } 

Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -