In the code below, is there a better way to reference the object instance from handleClick()
than pulling it in as a 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 the same thing, and the (non-accepted) answer is to pass a callback to $.on()
and call the handler from there, passing in the instance as a parameter like this:
bindEvents: function() {
var self = this;
$('button').on('click', function() {
self.handleClick.apply(self);
});
}
Is this technique of passing the instance around really the right way to do it, or is there still a preferred way besides the two I've shown?