jQuery Edge: Bind with a Different "this"
Brand new to jQuery SVN is the oft-requested feature of providing a different value for the “this” object in an event callback. Previously jQuery would always send the element as the value of “this” in the callback. You can utilize this new feature by passing the object you’d like to represent “this” in the callback as the last argument to either .bind()
or .live()
. Lets look at some example code!
The typical use-case for this functionality is that you’ll have an object (or a class) and you want to call a method of that class when you click on a particular element. However, the “this” object inside the method will be set to the element the event happened on. Usually in these situations you’d want the “this” object to represent the instance of your class, not the element. Here is an example that tries to illustrate this use-case.
// Create a class
var MyClass = function() {
// initialize the class
this.clicked = false;
this.element = null;
};
MyClass.prototype.click = function( event ) {
// handle the click event on an element
// the "this" object should represent the instance of
// the class, not the element the event happened on.
// the element can be retreived using the event.target
// or event.currentTarget
// set the clicked property to true
this.clicked = true;
// set the element property to the element that was clicked
this.element = event.target;
// cancel the event
return false;
};
// Create an instance of MyClass
var myInstance = new MyClass();
// Bind an event that calls the click method of myInstance
// and make sure the "this" object is set to myInstance
$("li").live("click", myInstance.click, myInstance);
As you can see from the example code the actual element the event happened on can still be retrieved via the event.target
or event.currentTarget
properties. Both of these properties are normalized/fixed to work cross-browser (as is the event.relatedTarget
property). In the example above I used the live
method of binding events but the same applies for the bind
method.