I was wondering what is the intended method for dealing with “this” references in callbacks frequently used in frameworks like jQuery and Backbone.js
Here is the simplified example I’m having a problem with, using Backbone.js and jQuery UI, but it is not really specific to these frameworks.
var MyView = Backbone.View.extend({
render: function() {
$('#mybutton').click(function() {
// My code in here
});
},
callMe: function() {
alert('Rawr!');
}
});
Now, how would I go about referencing the instance of MyView from inside the click handler? For example, how would I call “callMe” from inside the click handler? Outside the handler I’d just call this.callMe(); but “this” gets replaced with the DOM element inside the click handler. What is the best way to approach this?
The most effective way is simply to store the result of
thisin another variable, and then use that within the callback;Alternately, you can use either
jQuery.proxy()or the HTML 5 (beware of backwards compatability)Function.prototype.bind()method to define the value ofthis. Obviously then you’d loose the ability to usethisto refer to the DOM element, so would have to rely on thetargetproperty of theEventobject;Or: