jQuery 1.7: What happened to live and die?

In case you did not notice, in jQuery 1.7, the .live() and .die() methods have been deprecated. That does not mean you cannot use them but .on() and .off() are now the new and recommended ways to attach event handlers!

If you open the jQuery code file, you will observe that  .bind(), .live() and .delegate()  now map to .on(). Similarly .unbind(), .die() and .undelegate() now map to .off()

jquery-on

Why were .bind() and .live() deprecated?

The jQuery documentation states: For earlier versions, the .bind() method is used for attaching an event handler directly to elements. Handlers are attached to the currently selected elements in the jQuery object, so those elements must exist at the point the call to .bind() occurs. .on() provides a more streamlined, simplified and unified way of attaching events.

One of the biggest issues with .live() was performance. After using the .live() in your code, one would eventually end up attaching plenty of listeners. With .on(). since you have to specify a parent container, only one listener gets added.

StackOverflow user Interstellar_Coder has put forward a nice list of drawbacks of .live()
  • jQuery attempts to retrieve the elements specified by the selector before calling the .live()method, which may be time-consuming on large documents.
  • Chaining methods is not supported. For example, $("a").find(".offsite, .external").live( ... ); is not valid and does not work as expected.
  • Since all .live() events are attached at the document element, events take the longest and slowest possible path before they are handled.
  • Calling event.stopPropagation() in the event handler is ineffective in stopping event handlers attached lower in the document; the event has already propagated to document.
  • The .live() method interacts with other event methods in ways that can be surprising, e.g.,$(document).unbind("click") removes all click handlers attached by any call to .live()!
Changing from .live to .on()

Here’s an example of changing your existing .live() code to .on()

jquery-on-vs-live

See a Live Demo

You may also want to read jQuery 1.7 Custom Events Using .on Method





About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

2 comments:

Daniel Robbins said...

The new method .on() and .off() are generally like sugar that can simulate .bind(), .live(), or .delegate() based on how you contact it. As such .on() and .off() are new to me to which I am slowly getting into it.

Andrew said...

Thanks a lot for this informative post and highlighting the features jquery 1.7 is having.