The event flow defined by the "DOM2 level event" consists of three phases: the event capture phase, the target stage, and the event bubbling phase.
The first occurrence is event capture, which provides an opportunity to intercept the event. Then the actual target receives the event. The final stage is the bubbling phase, in which events can be responded to at this stage.
Application of Event FlowThe typical application for event flow comparison is event delegation. Event delegation takes advantage of event bubbling, specifying only one event handler to manage all events of a type.
Let's look at a common example, which is the DOM structure of an unordered list:
<ul> <li id="li1">我是第1个li</li> <li id="li2">我是第2个li</li> <li id="li3">我是第3个li</li> </ul>
Our need is to click on different columns to output different messages.
- The first approach: to
<li>
Add a click event to each, so that the event can be handled separately, showing different content.
document.getElementById('li1').addEventListener('click', function(e) { console.log('我是第一个li')}, false)document.getElementById('li2').addEventListener('click', function(e) { console.log('我是第2个li')}, false)document.getElementById('li3').addEventListener('click', function(e) { console.log('我是第3个li')}, false)
Clicking on each one <li>
will output the corresponding content.
- The second approach:
<li>
<ul>
Add a processing event to the element's parent element,
document.querySelector('ul').addEventListener('click', function (e) { console.log(e.target.innerText)}, false)
Clicking on each one <li>
will show the contents of the different <li>
Chinese text elements.
In this code, we only <ul>
add an onclick event handler for the element. Because all <li>
are <ul>
child nodes of the element and their events are bubbling, the Click event will eventually be processed by this function.
These two ways, the second has the advantage:
Lower upfront consumption. Because only one DOM element was obtained, only one event handler was added.
Consumes less memory. Each function is an object and consumes memory.
Better performance. The more objects in memory, the worse the performance.
If you want to add or subtract elements later, and you <li>
don't have to modify the event method, you can get the same result.
Therefore, the second way of comparison is recommended.
Events that are best suited to use event delegation techniques include,,,, click
mousedown
mouseup
keydown
, keyup
and keypress
. Although mouseover
and mouseout
events also bubble, it is not easy to handle them properly, and it is often necessary to calculate the position of the elements.
Resources:
JavaScript Advanced Programming (Third Edition)-Chapter 13th events
View Source: DOM2 Event-capture-bubbling
JS event flow mechanism bubbling and capturing