erichynds

Hi, I'm Eric Hynds, a front-end website developer living outside of Boston, Massachusetts. I'm passionate about developing functional, standard-compliant, and user-friendly websites.

Posts Tagged ‘livequery’

jQuery “Create” Event

Monday, June 14th, 2010

The livequery plugin allows us to bind events and general logic to all current and future elements. After the inclusion of live() in 1.3, an expansion of supported live event types in 1.4, and the introduction of delegate() in 1.4.2, the livequery plugin has more or less become deprecated. However, it still holds a special place in my heart because of it’s ability to listen for the creation of new elements.

Listening for new elements is most useful when you want to apply logic, like initializing a plugin, to elements that will be added via AJAX. Without livequery, this is easily accomplished by re-binding logic at the point where elements are injected:

// apply a plugin to all current div.foo's
$("div.foo").somePlugin();
 
// do some ajax
$.get("bar.htm", function( response ){
 
	// bind the plugin to the new element, and insert it into the DOM
	$(response).somePlugin().appendTo("body");
});

If you have multiple points of entry, however, this syntax can quickly become hard to maintain and is not very DRY. Livequery allows you to bind it once and forget about it:

// apply somePlugin to all current and future div.foo's
$("div.foo").livequery(function(){
	$(this).somePlugin();
});
 
// do some ajax
$.get("bar.htm", function( response ){
	$(body).append( response );
 
	// somePlugin will be applied to any additional 
	// div.foo's present in "response" automagically
});

To me the appearance of a new element always seems like an event, and it would be cool if this was something you could bind to. The idea here is that once jQuery injects an element into the DOM, any handlers attached to the element’s selector would fire. Luckily, most of jQuery’s DOM manipulation methods (append, prepend, after, before, etc.) eventually funnel down into the $.fn.domManip method. With this in mind, I duck punched $.fn.domManip, added a new “create” special event, making this type of syntax possible:

// when a new div.foo element enters the DOM, call somePlugin() on it.
$("div.foo").live("create", function(){
	$(this).somePlugin();
});

(more…)