Explanation of event bubbling and capture

When an event occurs on an element that has a parent element, modern browsers run two different phases – the capture phase and the bubble phase. In the capture phase:

  • The browser checks the outermost ancestor of the element<Window>, whether one was registered during the capture phaseonclickEvent handler, if so, run it.
  • And then, it moves to<Window>Click on the element’s next ancestor and do the same, then click on the element and the next ancestor, and so on until you reach the actual clicked element.

In the bubbling phase, the opposite is true:

  • The browser checks to see if the actual clicked element registered one in the bubble phaseonclickEvent handler, if so, run it
  • It then moves on to the next direct ancestor element and does the same, then the next, and so on, until it arrives<Window>Elements.

Event delegation

Event delegation, in general, is to make a response to an event or a group of elements function entrusted to its parent layer or outer element, real binding events is the outer element, when the incident response to need binding element, through event bubbling mechanism which triggers it on the outer element binding event, and then in the outer elements to perform the function.

advantages

1. Reduce memory consumption (save listening number)

Such as:

If you want to add click events to 100 buttons, what do you do?

If you add click events to each button, it is very expensive in memory and requires a lot of performance in terms of efficiency;

Therefore, we can listen to the parent element of the 100 buttons and wait to bubble to see if target is one of the 100 buttons.

So event delegation can reduce a lot of memory consumption and save efficiency.


2. You can listen for dynamic elements

Such as:

You want to listen for click events for elements that do not currently exist.

A: Listen for ancestors, and then click to see if it is the element I want to listen for.