Jquery Plugin Object: Attached An Event Handler Via .on() And Now Have A Scope Issue Of This. (the Main Plugin Object)
I am attempting to move away from spaghetti code in my jQuery plugins and work in a more structured manner. I am doing so by using the basic boilerplate template found here: https:
Solution 1:
I recently ran into this issue, and I found a few work-arounds.
JavaScript's bind
works in modern browsers:
bindEvents : function (base) {
this.$el.on('click', {base: base}, this.myFunction.bind(this));
},
myFunction : function () {
console.log(this); // Plugin context
}
jQuery's proxy
function works in older browsers:
bindEvents : function (base) {
this.$el.on('click', {base: base}, $.proxy(this.myFunction, this));
},
myFunction : function () {
console.log(this); // Plugin context
}
You can also create the event handler function inside your bindEvents
function, and give yourself access to both contexts:
bindEvents : function (base) {
var instance = this;
var myFunction = function() {
console.log(this); // element contextconsole.log(instance); // Plugin context
};
this.$el.on('click', {base: base}, myFunction);
}
Post a Comment for "Jquery Plugin Object: Attached An Event Handler Via .on() And Now Have A Scope Issue Of This. (the Main Plugin Object)"