How to write OOP JS and use jQuery at the same time
javascript, jquery, oop
Solution
jQuery has `$.proxy` that can be used like so:
function MyClass() {
this.clicked = $.proxy(this.clicked, this);
}
MyClass.prototype = {
clicked: function(e) {
alert("Here 1");
this.test();
e.currentTarget; //this replaces "this"-the keyword used in "non OOP" contexts
//see http://api.jquery.com/event.currentTarget/
},
init: function() {
$("#someSpan").click(this.clicked);
},
test: function() {
alert("Here 2");
}
}
When you create an instance, that instance gets its own `.clicked` function that shadows the generic one in the prototype. It will always have same `this` binding no matter how you call it. So you can pass `this.clicked` all over the place and have it work.
Problem
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 ?