jQuery Edge: Live Events now with Data
Friday, May 8, 2009
In jQuery 1.3.3 1.4 the .live() method will have the ability to pass data along just like you might do with .bind(). The .bind() (and now .live()) method takes an optional second argument called “data”. The data can then be accessed within the event handler by using the event.data property. Here is what the code would look like to use this feature.
// The data
var eventConfig = {
selectedClass: "selected"
};
$("li").live("click", eventConfig, function( event ) {
// Retreive selectedClass from the event data
var selectedClass = event.data.selectedClass;
// Toggle the class amongst the siblings
$(this).addClass( selectedClass )
.siblings().removeClass( selectedClass );
});
So in the previous example, trivial as it may be, each time you click an “li” element the selected class defined in the eventConfig is assigned to the clicked element and removed from the siblings.
Posted in jQuery, jQuery Edge with 5 comments
Why wouldn’t I just refer to eventConfig.selectedClass directly?
By aaron on Saturday, May 9, 2009 at 12:26 PM
@aaron, The intent of the example was not to provide a good use-case for utilizing the optional data argument, but instead to provide a simple example of how to use it. I believe the usage of the optional data argument is going to depend on your web site/application architecture.
One use-case is that the optional data argument provides a way for events to be easily customizable. Perhaps in the example there isn’t an “eventConfig” variable and the developer just passes in the name of the selected class they’d like to use.
Not sure I’ve done the potential functionality of using the optional data argument justice.
By Brandon Aaron on Saturday, May 9, 2009 at 10:04 PM
Definitely need to be passed on the function if you want to call it eventConfig directly.
Imagine it as a class. The eventConfig will act as a static variable, though it’s not 100% similar or even close to the way static variable act in OOP.
By Wendy Novianto on Friday, June 26, 2009 at 07:11 PM
I think this will also help in writing OOP event handlers for live events. Prior to 1.4, AFAIK , we could not do this:
By Ravi on Saturday, February 27, 2010 at 08:18 AM
@Ravi, In jQuery 1.4 there is also a method called jQuery.proxy. To use it just change this line in your example:
To this:
Now the
thiswill be correctly set.By Brandon Aaron on Saturday, February 27, 2010 at 08:27 AM