Issue regarding live event
Asked Answered
H

2

6

I was just reading http://api.jquery.com/event.stopPropagation/

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

I was a bit confused with this statement, Can someone please explain me the same with some example?

Hereby answered 16/5, 2011 at 16:20 Comment(1)
Related question (under the hood): #1687796Longheaded
F
4

Live method binds a handler to the document, and identifies which element triggered the event from the event.target property.

So the actual handler is at the top (in terms of hierarchy).

The stopPropagation stops the bubbling from going up the DOM hierarchy, but since the handler is at the top already (in the .live case) there is no upper place to bubble to ..


example attempt ..

- document
  - div
    - link

you bind a click event handler to the link (with the bind or click method).

When you click the link, the handler is triggered, but in addition the click event goes up the DOM until it reaches the document, and will also trigger click handlers bound to the div and document. (unless you use the .stopPropagation)

Alternatively if you use the .live method to bind the event handler, it will be bound to the document. If you now click the link, the event (which will not fire right away, since no handler is bound to it) will naturally go up the DOM (triggering the click handlers it encounters). Once it reaches the document it will trigger our own handler. But there is no upper to go, so the stopPropagation is useless at this point.

Firehouse answered 16/5, 2011 at 16:24 Comment(0)
B
2

HTML:

<div id="outer">
   <div id="inner">
       <span>.live() version</span>
   </div>
</div>

<div id="outer2">
   <div id="inner2">
       <span>.delegate() version</span>
   </div>
</div>

JS:

$(function(){

   $('#inner2').delegate('span', 'click', function(e){
      e.stopPropagation(); // indeed, no alert!
   });

   $('span').live('click', function(e){
      e.stopPropagation();
      // we would expect the propagation to stop here, so no alert, right?
   });

   $('#outer2, #outer').click(function(){ alert("Don't reach me!"); });

});

Example: http://jsfiddle.net/knr3v/2/

.live() only does its magic once the event has already bubbled, so stopping the event from propagating is useless - it's too late, it has already reached the top of the tree and propagated...

Bunche answered 16/5, 2011 at 16:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.