Event flow sequence

Event flow is the order in which web elements receive events. The event flow specified in “DOM2-level events” includes three stages:

  • Event capture phase
  • In the target stage
  • Event bubbling phase

Event capture occurs first, providing an opportunity to intercept the event, followed by the actual target acceptance of the event, and finally the event bubbling phase,

Event capture

const dom = document.getElementById('#main')
dom.addEventListener('click', (event) => {
  console.log(event)
}, true)
Copy the code

How do component events capture

function myEvent(event) {
  event.stopImmediatePropagation()
}
Copy the code

The event bubbling

const dom = document.getElementById("#main")
dom.addEventListener('click', (event) => {
  console.log(event)
}, false)
Copy the code

How do I prevent events from bubbling up

function myEvent(event) {
  event.stopPropagation()
}
Copy the code

When container elements and nested elements invoke event handlers, both in the capture phase and in the bubble phase: Events execute event handlers in the sequence of DOM event streams:

  • The parent trap
  • The child capture
  • Children bubble
  • The parent bubbling

How are events implemented

A publish-subscribe model, in which event-related code is read when the browser loads, but not executed until a specific event is triggered

On the Web side, we often see DOM events

  • Dom0-level events, which bind on-events directly to HTML elements, such as onclick. If you cancel, dom.onclick = null, you can only have one handler for an event, and the latter will override the previous one
  • Dom2-level events, event listening via addEventListener, event removal via removeEventListener. An event can have multiple event handlers, executed in sequence, capturing events and bubbling events
  • DOM3 level events, added event types, such as UI events, focus events, mouse events

Event delegation

Event delegation can reduce the monitoring of events and optimize the operation performance. Its principle is to use event bubbling to give the parent an event listener. The click-level child element bubbling to the event of the parent element, and then determine the type of event element clicked at the moment to obtain the desired value