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()
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 thedocument
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 todocument
. - 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()
Tweet
2 comments:
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.
Thanks a lot for this informative post and highlighting the features jquery 1.7 is having.
Post a Comment