Home > Article > Web Front-end > Several details of JavaScript events
1. Is it capturing or bubbling? Yesterday I was asked a question: How many stages does the event flow have? How many times did the event occur during these stages?
The question is very simple, but it’s a bit confusing as to how many times the event occurred. I always feel that capturing can also trigger events, and bubbling can also trigger events, but the event only happened once! So I wrote an article to sort it out. Students who know this very well can skip it.
Sub-question 1: How many stages does the event flow have?
The event flow specified by "DOM2-level events" includes three stages: event capture stage, target stage and event bubbling stage.
1. IE browsers before IE9 only support the last two stages, which are the target stage and the event bubbling stage. This sequence is easy to understand. Events are received on the node with the deepest nesting level, and then propagated up to the parent node step by step.
2. Another event stream proposed by the early Netscape team is called event capture. That is, the top-level node should receive the event earlier and gradually propagate to the node with the deepest nesting level, that is, the event capture stage and the target stage
3. Modern browsers such as chrome, ff, IE9, etc. support the entire three stages.
Sub-question 2: How many times did the incident occur in these stages?
When an event occurs, the event flow of "DOM2-level events" will go through three stages (capture -> on target -> bubbling), but not every stage can occur. For a node, if the third parameter of the addEventListener method is true, the event occurs in the capture phase; if it is false, the event occurs in the bubbling phase. So the event only happened once!
If the outer node wants events to occur in both the capture and bubbling phases, then register it twice.
Incidentally, "DOM level 0 events" (elem.onclick = function () {...}) also have event bubbling.
2. Registration order of events
Register multiple events on the same node,
Use addEventListener, the order of occurrence is based on the order of events being added;
Use attachEvent, the order of occurrence is reverse Those who come over, those who register later will happen first.
3. Remove events
The method of removing events removeEventListener and detachEvent are for the same callback function when the event occurs, so the use of anonymous functions when registering events cannot be removed.