Usually (if not always), when jQuery allows you to add a callback to some JS event like click, in the callback function they change the “meaning” of this into the DOM element which triggered the event.
This can be quite useful, but it will stand in your way when you write OOP code in js, like in this example:
function MyClass() {}
MyClass.prototype = {
init: function() {
$("#someSpan").click(this.doSomething);
},
doSomething: function() {
alert("Here 1");
this.test();
return false;
},
test: function() {
alert("Here 2");
}
}
In this example, this.test() will not work, because this is not anymore an instance on MyClass but instead a jQuery DOM element (the span).
My questions are: is there a way to continue writing OOP code in JS using this pattern and also use jQuery? And: why is jQuery changing this in the callback function when it could as easily send the jQuery DOM element as first argument ?
jQuery has
$.proxythat can be used like so:When you create an instance, that instance gets its own
.clickedfunction that shadows the generic one in the prototype. It willalways have same
thisbinding no matter how you call it. So you can passthis.clickedall over the place and have it work.