views:

58

answers:

2

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'

+4  A: 

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.

redsquare
A: 

The reason why this changes is because of how javascript scoping works. It is better to understand this fundamental concept if you want to do any serious js.

Explanation of this concept here:

http://stackoverflow.com/questions/710542/jquery-javascript-this-pointer-confusion/710621#710621

Aaron Qian