JQuery: binding handlers for current and future element’s events
The latest version of JQuery (1.3 at the time of writing) added a really cool feature: binding a function to current and future elements’ events. Until now, we’ve seen how we can use the bind method for setting up an event handler. For instance, the following snippet will hook up the click event of all existing spans:
$("span").click(function() { alert("clicked"); });
Now, the problem is that if you add any new span to the page, then you’ll also need to add code for hooking up the event. The live method solves this problem and will bind all existing and future elements that match the initial criteria to a specific function. Its syntax is really similar to the bind method, as you can see from the next snippet:
$("span").live("click", function() { alert("clicked"); });
There are some gotchas that might affect the use of this method. For instance, currently the method will only work against selectors. So, if you have something like this:
$("span").parent().live("click", function() { alert("clicked"); });
then you’d be disappointed because things won’t work as expected. There’s also the bubbling thingy, but that will only make sense after we discuss event propagation (which we’ll leave for a future post). Unlike bind, where the first parameter can be a space delimited string with the name of several events, with live you can only pass an event at a type. And finally, you should also keep in mind that live supports only a subset of all the existing events (take a look at the docs for the complete list).
As you might expect, there’s also a method for cancelling the work performed by live. Canceling live events depends on the invocation of the die method. It works in similar fashion to the unbind method. If you call it without parameters, you’ll cancel all the live events that have been previously setup.
If you pass the name of the event, then all live events of that type will be cancelled. You can also pass a function reference as a second parameter. In that case, you’ll end up cancelling only that handler. It’s important to keep in mind that the die method will only affect handlers that have been previously setup through the live method (ie, all handlers previously setup with the bind method will still keep firing in the future).