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
Post a Comment