What is the event model of jQuery?

I’ve been confused with javascript event model for long time. You must know there are two event models in javascript: capturing model and bubbling model. Every article describing event model of Javascript says that, and you will get an illusion that some browsers implement a bubbling model and others implement a capturing model. In capturing model, event flows from parent element to child element(i.e. from top to bottom) so event handlers  of parent are called first, while in bubbling model, event flows from child element to parent element(i.e. from bottom to top) so event handlers of child element are called first.  The reality is there is no separated event models in modern browsers. There is only one event model nowadays – the one specified by DOM Level 2, which includes both the capturing phase and the bubbling phase. The even handlers registered by old onclick-like properties and the event handlers registered by  the new addEventListener function without the third parameter, will be triggered in the bubbling phase, while the event handlers registered by addEventListener with the third parameter set to true(see the following code), will be triggered in the capturing phase(and will not be triggered for the second time in later bubbling phase). The internal logic of event flow keeps the same: event flows from top to target then flows back to the top.

element.addEventListener('click',eventhandler,true);

true means the event handler will be called in capture stage; false means the event handler will be called in bubble stage of event.

In jQuery, there are two methods to add an event handler for an element:

  1. $(element).click(function(){});
  2. $(element).bind('click',function(){});

Both methods bind the function which is called at the bubbling stage of event.

Here is a good tutorial about javascript event model. Other posts on javascript event model are rubbish and not worth reading. If you want to know how to add event listeners to an element, or want to know the difference between the onclick assigned event handlers and addEventListener registered event handlers, you can also read this post.

If you like my content, please consider buying me a coffee. Buy me a coffeeBuy me a coffee Thank you for your support!

Leave a Reply