JQuery.bind events triggered by events or events

All I know in the Dom 2 level event model is event capture and the event bubble. but I just can't figure out how jquery handles them. Therefore, I conducted an experiment with the .bind method. here is my code. please view it.

 <script> $(function() { $('*').each(function(){ var current = this; $(this).bind("dblclick",function(event){console.log('Capture for ' + current.tagName + '#'+ current.id + ' target is ' + event.target.id);}); }); }); </script> <body id="greatgrandpa"> <div id="grandpa"> <div id="pops"> <img id="example" src="designer/templates/thumbnails/2ColsTemplate.PNG" /> </div> </div> </body> 

the output looks below

 Capture for IMG#example target is example Capture for DIV#pops target is example Capture for DIV#grandpa target is example Capture for BODY#greatgrandpa target is example Capture for HTML# target is example 

When I use event.stopPropagation(); , the event handler will stop the dblclick event.

But I have 2 questions. In accordance with the order of writing the logs, I guessed that the bind method causes the event to fire in the event bubble (from bottom to top of the dom peak), and not at the top of the event (from top to bottom). Another question: is there a chance that the event will be fired during the event capture period? thanks.

thanks.

+6
source share
2 answers

jQuery only supports the event bubbling phase, not the event capture phase, not least because IE has not supported capture for a long time. What your code shows you is bubbling, not capturing.

Capture goes from document to the element on which the event occurred; then the bubble starts from the element and bubbles again to document , so you see the events in that order (which is the bubbling phase).

+11
source

The previous answer is correct. However, there is an easy workaround. To get the same effective result, you can stop distributing to stop bloating the event, trigger the event on the parent, and then execute the required code to happen after the events on the parent.

for your example, if you want to effectively invert the execution of handlers:

  $('*').each(function(){ var current = this; $(this).bind("dblclick",function(event){ // stop the event propagation event.stopPropagation(); // execute allow the event to be executed on parent objects var parent = $(event.target).parent(); if(parent) { parent.dblclick(); } console.log('Capture for ' + current.tagName + '#'+ current.id + ' target is ' + event.target.id);}); }); 

One drawback of this methodology is that if a parent was defined with a capture event handler, a capture has already occurred and an event call on the parent call will cause the capture handler to re-execute. Therefore, this should only be used when you know or control the events announced for all elements of the parent's purpose.

0
source

All Articles