Advertisement
JavaScript & AJAX

Quick Tip: The Difference Between Live() and Delegate()

by

In jQuery 1.3, the team introduced the live() method, which allows us to bind event handlers to elements on the page, as well as any that might be created in the future dynamically. Though not perfect, it definitely proved to be helpful. Most notably, live() bubbles all the way up, and attaches the handler to the document. It also ceases to work well when chaining method calls, unfortunately. Delegate() was introduced in version 1.4, which almost does the same thing, but more efficiently.

We'll examine the specific differences between the two methods in today's video quick tip. Thanks to the FireQuery Firebug extension, we'll have the tools to more easily understand how each method functions.

Alternate Viewing Options

<ul id="items">
	<li> Click Me </li>
</ul>
// Bind attaches an event handler only to the elements
// that match a particular selector. This, expectedly,
// excludes any dynamically generated elements.
$("#items li").click(function() {
	$(this).parent().append("<li>New Element</li>");
});


// Live(), introduced in 1.3, allows for the binding
// of event handlers to all elements that match a 
// selector, including those created in the future.
// It does this by attaching the handler to the document.
// Unfortunately, it does not work well with chaining.
// Don't expect to chain live() after calls like 
// children().next()...etc. 
$("li").live("click", function() {
	$(this).parent().append("<li>New Element</li>");
});	


// Delegate, new to version 1.4, perhaps should have been a complete 
// replacement for Live(). However, that obviously
// would have broken a lot of code! Nonetheless, 
// delegate remedies many of the short-comings
// found in live(). It attaches the event handler
// directly to the context, rather than the document. 
// It also doesn't suffer from the chaining issues
// that live does. There are many performance benefits
// to using this method over live().
$('#items').delegate('li', 'click', function() {
	$(this).parent().append('<li>New Element</li>');
});	


// By passing a DOM element as the context of our selector, we can make
// Live() behave (almost) the same way that delegate()
// does. It attaches the handler to the context, not
// the document - which is the default context.
// The code below is equivalent to the delegate() version
// shown above.
$("li", $("#items")[0]).live("click", function() {
	$(this).parent().append("<li>New Element</li>");
});

Conclusion

This can definitely be a confusing topic. Please feel free to ask questions, or discuss within the comments. Thanks so much to Elijah Manor for clarifying a few things for me on this topic!

Related Posts
  • Code
    HTML5
    HTML5: Battery Status APIPdl54 preview image@2x
    The number of people browsing the web using mobile devices grows every day. It's therefore important to optimize websites and web applications to accommodate mobile visitors. The W3C (World Wide Web Consortium) is well aware of this trend and has introduced a number of APIs that help with this challenge. In this article, I will introduce you to one of these APIs, the Battery Status API.Read More…
  • Code
    HTML & CSS
    Intro to Shadow DOMShadow dom retina preview
    Take any modern web page and you will notice that it invariably contains content stitched together from a variety of different sources; it may include the social sharing widgets from Twitter or Facebook or a Youtube video playing widget, it may serve a personalized advertisement from some ad-server or it may include some utility scripts or styles from a third party library hosted over CDN and so on. And if everything is HTML based (as is preferred these days) there is a high probability of collisions between the markup, scripts or styles served from various sources. Generally, namespaces are employed to prevent these collisions which solve the problem to some extent, but they don't offer Encapsulation.Read More…
  • Code
    Tools & Tips
    Tips to Avoid Brittle UI TestsUi test retina preview
    In the last article I talked about a few ideas and patterns, like the Page Object pattern, that help write maintainable UI tests. In this article we are going to discuss a few advanced topics that could help you write more robust tests, and troubleshoot them when they fail:Read More…
  • Code
    JavaScript & AJAX
    Integrating a JS Build Process Into MSBuild in Visual Studio 2012 ExpressMsbuild retina preview
    I've been working with ASP and ASP.NET for about ten years now, starting with ASP classic and settling on .NET 2.0 as my favorite. My new year resolution this year (2013) was to upgrade my .NET work to .NET 4.0 using Visual Studio 2012 Express and really get to grips with MSBuild, so that I can concatenate and minify my JavaScript files as part of the normal build process of a .NET project, in Visual Studio. My first love is to use Ant in NetBeans with a PHP or JSP platform for this kind of work, but my company's main website runs on a .NET platform and it's time to update it, so I decided to bite the bullet and dive back in to some serious study of creating a fully integrated build process using MSBuild. This tutorial will show you how to edit your Visual Studio 2012 Express project file to include your own separate build file which will perform the now widely familiar process of concatenating and minifying a set of JavaScript modules into one file ready for deployment. Read More…
  • Code
    JavaScript & AJAX
    Building Large, Maintainable, and Testable Knockout.js ApplicationsKnockout
    Knockout.js is a popular open source (MIT) MVVM JavaScript framework, created by Steve Sandersen. Its website provides great information and demos on how to build simple applications, but it unfortunately doesn't do so for larger applications. Let's fill in some of those gaps!Read More…
  • Code
    JavaScript & AJAX
    jQuery Succinctly: Events & jQueryJquery cover
    Not Limited To a Single ready() Event It is important to keep in mind that you can declare as many custom ready() events as you would like. You are not limited to attaching a single .ready() event to the document. The ready() events are executed in the order that they are included.Read More…