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?
The object can be passed as eventData to on(), like so:
var Widget = function () {
this.property = 'value';
this.bindEvents();
}
Widget.prototype = {
bindEvents: function () {
$('button').on('click', {o: this}, this.handleClick);
},
handleClick: function (e) {
var widgt = e.data.o;
console.log(widgt.property);
}
}
window.Widget = new Widget();
FIDDLE
This keeps the scope of the event handler as it should be.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With