1. Event mechanism
An event is an action or event that occurs in the system during programming. The system triggers a signal when an event occurs and provides a mechanism for automatically loading an action. Each event has an event handler (sometimes called an event listener), which is a block of code that runs when the event is triggered. Strictly speaking, event listeners listen for events to occur, and event handlers react to events.
2. The DOM event stream
Event Flow refers to the order in which web elements receive events. Event flows can be divided into two mechanisms:
- Event Capturing
- Event Bubbling
When an event occurs, it propagates between child and parent elements. This spread is divided into three stages:
- Capture phase: the phase in which events propagate from the Window object down to the target node;
- Target phase: the phase in which the actual target node is processing events;
- Bubbling phase: The phase in which events propagate bottom-up from the target node to the Window object.
Event capture refers to triggering the event response function from the outermost element (the ancestor element), down to the target element. The schematic diagram is as follows:
The event bubbling process is the inverse of event capture. When an event occurs, the target element (the most immediate element) is fired, and then the event response function of its parent element is fired, cascading back to the ancestor element.
In 2002, the W3C released a standard stating that browsers should support both call sequences, capture first and bubble later. The schematic diagram is as follows:
When the < TD > click event occurs, the red “Capture Phase” will be the first:
1.Document
2.<html>
3.<body>
4.<table>
5.<tbody>
6.<tr>
7.< TD > (the element actually clicked)Copy the code
Trigger their click events sequentially from the top down.
After reaching the “Target Phase”, the green “Bubble Phase” is continued, and the reverse direction is uploaded from < TD > all the way to the Document, and the whole event flow ends there.
3. Prevent the event from spreading
In nested elements, where each element has an event handler, when the inner element is clicked, all the handlers are executed at the same time because the event appears in the DOM tree. To prevent this, interrupt bubbling with e.topPropagation () so that the browser no longer goes up.
Some events have default actions associated with them. For example, clicking a link browser takes you to the target of the link, clicking a form submit button browser submits the form, etc. The preventDefault() method of the event object can be used to prevent this default action. However, blocking the default action does not stop event propagation, and events continue to propagate into the DOM tree as usual.
But some events do not block the default action. For example, MDN searches for scroll event and sees Bubbles and Cancelable. Bubbles means whether the event Bubbles, and all Bubbles can be cancelled. Cancelable means whether the developer can block the default event.
4. Event delegation
Since events propagate up to the parent node during the bubbling phase, you can define the listener function of the child node on the parent node and let the listener function of the parent node process events of multiple child elements uniformly.
advantages
- Reduce memory consumption and improve performance
If you want to add click events to 100 buttons, if you bind a function to each button, it will be very expensive in memory and cost a lot of performance in terms of efficiency. Using event delegation, we only need to give the 100 buttons the parent container binding approach, so no matter which a descendant elements, click will according to the transmission mechanism of transmission of bubbling, click behavior triggers the container, and then the corresponding method to carry out, according to the event source, we can know is who, click to do different things. A code example is as follows:
<div id="div1">
<button>click 1</button>
<button>click 2</button>
<button>click 3</button>
<button>click 4</button>
<button>click 5</button>
</div>
<script>
div1.addEventListener('click'.(e) = > {
// Assign the target element to t
const t = e.target
// Determine if the target element matches
if (t.tagName.toLowerCase() === 'button') {
console.log('Button content is :'+ t.textContent); }});</script>
Copy the code
- You can listen for dynamic elements
Suppose we want to listen for a click on an element that doesn’t currently exist, we can simply listen on the element’s parent container and wait for the click to see if it’s the element I want to listen on. A code example is as follows:
<div id="div1">
</div>
<script>
setTimeout(() = >{
// add a button inside div1
const button = document.creatElement('button')
button.textContent = 'click 1'
div1.appendChild(button)
},1000)
div1.addEventListener('click'.(e) = >{
const t = e.target
if(t.tagName.toLowerCase() === 'button') {console.log('button is click')}});</script>
Copy the code
Encapsulating event delegate
<div id="div1">
</div>
<script>
setTimeout(() = >{
const button = document.creatElement('button')
button.textContent = 'click 1'
div1.appendChild(button)
},1000)
on('click'.'#div1'.'button'.() = >{
console.log('Button is clicked')})function on(eventType, element, selector, fn){
// Determine if element is not an element
if(! (elementinstanceof Element)){
element = document.querySelector(element)
}
element.addEventListener(eventType,(e) = >{
const t = e.target
//matches checks whether an element satisfies a selector
if(t.matches(selector)){
fn(e)
}
})
}
</script>
Copy the code
Reference for this article:
The event mechanism of the JavaScript Event Trilogy
JavaScript ramblings about the DOM event mechanism
DOM event mechanism
DOM event mechanism & event delegate