A problem I regularly come across writing javascript using jQuery is that when a method of an object involves adding an event listener ‘this’ changes from being a reference to the object, to being a reference to the DOM element that triggered the event.
Currently if I want to refer to the object from within the event handler I do something like this:
var theObject = this;
$('selector').click(function() {
theObject.methodToApply();
$(this).css('background','red');
});
Is there a better way to handle the fact that events always want to reassign ‘this’
What your doing is the standard way of dealing with it in jQuery. The next version of jQuery will give you the ability to define what you want the this context to be. Read Brandons blog post for more info.