Event bubbling and event capture mechanism in JavaScript

Event bubbling and event capture mechanisms in JavaScript are very important concepts in development. Mastering these two mechanisms can better understand event processing and DOM operations. This article will take a deep dive into event bubbling and event capturing in JavaScript, including how they work, how to use them, and their pros and cons.

1. What is event bubbling and event capture mechanism?

Before understanding event bubbling and event capture mechanism, we need to understand what is DOM. DOM (Document Object Model) is a way to represent HTML and XML documents. Through DOM, we can manipulate and modify the content and structure of HTML and XML documents. In an HTML document, each HTML element is a DOM node, and the node can contain child nodes (that is, the content inside the element), or it can have a parent node. Each DOM node can trigger events, such as mouse click, keyboard input, page load, etc.

When an event fires on a DOM node, the event bubbles up or gets caught down. Event bubbling means that the event is passed from the innermost element to the outer element, while event capture is passed from the outermost element to the inner element. In JavaScript, you can add an event handler to an element through the addEventListener() method, and specify whether to use event bubbling or event capture. By default, event handlers employ event bubbling.

2. Event bubbling mechanism

Event bubbling refers to the transmission of events from the innermost element to the outer element. For example, if we click on the innermost child element in a nested HTML structure, the event will start from the child element and pass to the parent element in turn until it reaches the root node of the entire document. During this process, each node has a chance to process this event.

For example, consider the following HTML code:

<div id="outer">
  <div id="middle">
    <div id="inner"></div>
  </div>
</div>

If we bind a click event on the inner element, then when the inner element is clicked, the event will bubble from the inner element, then pass to the middle element and the outer element in turn, and finally pass to the root node of the entire document. In this process, each node can add an event handler to it through the addEventListener() method to handle this event.

The advantage of the event bubbling mechanism is that it allows the event handler to stop the propagation when the event bubbles to a certain node. For example, we can use the event.stopPropagation() method in the event handler to prevent the event from continuing to propagate upwards, so that the event can be prevented from being processed by the event handler of the parent element or ancestor element.

3. Event capture mechanism

Event capture refers to the transmission of events from the outermost element to the inner element. Unlike event bubbling, during event capture, each node has a chance to handle the event until the event is delivered to the innermost element.

Compared with the event bubbling mechanism, the advantage of the event capture mechanism is that it allows us to process the event before it reaches a certain node. For example, we can use the event.preventDefault() method in the event handler to prevent the default behavior of the event, so that the browser can avoid the default behavior of the event, so as to implement custom operations.

To use the event capture mechanism, you need to set the third parameter of the addEventListener() method to true, indicating that the event capture mechanism is used. For example, the following code will use the event capture mechanism to handle click events:

var outer = document.getElementById('outer');
var middle = document.getElementById('middle');
var inner = document.getElementById('inner');

outer.addEventListener('click', function() {
  console.log('outer');
}, true);

middle.addEventListener('click', function() {
  console.log('middle');
}, true);

inner.addEventListener('click', function() {
  console.log('inner');
}, true);

In the above code, we added an event handler for each of the outer, middle and inner elements and set the event capture mechanism to true. In this way, when we click on the inner element, the event will be captured from the outer element, passed to the middle element and the inner element in turn, and finally reach the target element inner. During this process, each node has a chance to process this event.

Fourth, the application of event bubbling and event capture

In actual development, we usually use event bubbling and event capture mechanisms to achieve the following functions:

1. Event delegation: Bind the event handler to the parent element, and use the event bubbling mechanism to handle the events of the child elements. This approach can greatly reduce the number of event handlers and improve code efficiency and maintainability.

For example, we can bind the click event handler to the root node of the document, and handle the click events of all elements through the event bubbling mechanism. In this way, when we need to add new elements to the page, we only need to add the elements to the corresponding parent elements, without adding event handlers to the elements.

document.addEventListener('click', function(event) {
  if (event.target.matches('.button')) {
    console.log('button clicked');
  }
});

2. The default behavior of the event: use the event capture mechanism to prevent the default behavior of the event and realize the custom operation. For example, when submitting a form, we can use the event capture mechanism to verify whether the data in the form is legal. If the data is not legal, prevent the default behavior of the form and prompt the user to modify the data.

var form = document.getElementById('myForm');
form.addEventListener('submit', function(event) {
  if (!validateForm()) {
    event.preventDefault();
  }
}

3. Stop the propagation of the event: use the event capture mechanism to prevent the propagation of the event, so that the event is only processed on the current node. For example, when an element is clicked, we can use the event capture mechanism to stop the propagation of the event, so as to avoid other elements from interfering with the processing of the event.

var button = document.getElementById('myButton');
button.addEventListener('click', function(event) {
  console.log('button clicked');
  event.stopPropagation();
});

In the above code, we added a click event handler for the button and used the event capture mechanism to prevent the event from propagating. This way, when we click on the button, the event will only be fired on the button and other elements will not react to the event.

In short, event bubbling and event capture mechanism are important concepts in JavaScript, which can help us better handle events in the page. In actual development, we should choose which mechanism to use according to specific scenarios to achieve our needs.

Guess you like

Origin blog.csdn.net/tyxjolin/article/details/130526323