Question

I figure other developers have run into this before. We have a large code base with many components following this pattern:

$('#elm').on('click',function($e){
    $e.stopPropagation();
    //... do stuff (i.e. Open something);
});

$('html').on('click',function($e){
    //... do oposite of stuff (i.e. Close something);
}

Our issue is, all the stopPropagation's across the site are stopping closing of other components. What we really want is a mechanism to only block the click handler for this component but not for others.

I'm looking for a solution which is the easiest to implement right now to fix our bugs and for our Multi-developer team to follow in the future.

Was it helpful?

Solution

The .live() method handles events once they have propagated to the top of the document, it is not possible to stop propagation using live events this allows you to do hack and take advantage of this because the .live() method binds a handler to the $(document), and identifies which element triggered the event up at the top of the hierarchy using the event.target property.

The stopPropagation stops the propagation from bubbling up the DOM hierarchy, but since the handler is at the document level there is no upper place to propogate to.

On the other hand note that events handled by .delegate() will bubble up to the elements to which they are binded to; 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()

See this example: http://jsfiddle.net/knr3v/2/

Therefore you can use the live and delegate method instead of click, bind, on method to do exactly what you are explaining.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top