Reputation: 10342
I wrote a sample JavaScript program to demostrate the confusingly different event bubbling behavior of jQuery's function, click
, delegate
and live
.
Here is the demo page.
For each function, there is a wrapper and a click link in the wrapper, both of which are registered with click event functions.
I notice that
stopPropagation
in live
and delegate
does not prevent event bubblinglive
and delegate
, the click event in the wrapper is fired first and the click link next. However, this order is reversed for click
function.Can anyone explain these two phenomenon?
The sample is using jQuery 1.6.4, but you can adjust the version.
Upvotes: 1
Views: 186
Reputation: 30187
If you understand the implementation of live and delegate then you would understand the reason for this difference. Live and delegate in a way are not attached to the element because the element is not there at the time of binding they are attached to either the root or a specific parent respectively and hence the difference. And they make use of event bubbling so that when event bubbles from child to the root or a specific parent it executes for the newly added element see this blog entry for a detailed view around this:
http://www.alfajango.com/blog/the-difference-between-jquerys-bind-live-and-delegate/
Upvotes: 1
Reputation: 39872
To start, live is deprecated in favor of on and delegate in jQuery 1.7+. I would stop using live
now rather than later. The docs linked above are actually very informative and do a great job of explaining how these functions work.
Delegate and live both rely on bubbling. Which is how they differ from click. The event has bubbled up to them. Delegate is superior to live because you tell it to monitor a specific parent whereas live bubbles all the way up to the document level. Very expensive.
The jQuery documentation is worth quoting here:
Since the .live() method handles events once they have propagated to the top of the document, it is not possible to stop propagation of live events. Similarly, events handled by .delegate() will propagate to the elements to which they are delegated; event handlers bound on any elements below it in the DOM tree will already have been executed by the time the delegated event handler is called. These handlers, therefore, may prevent the delegated handler from triggering by calling event.stopPropagation() or returning false.
Upvotes: 2