Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to implement event Monitoring and event delegation in javascript

Shulou Source: shulou.com Published: 2022-05-31 11:48:10 11月03日 Update

This article mainly introduces the javascript event monitoring and event delegation how to achieve the relevant knowledge, the content is detailed and easy to understand, the operation is simple and fast, has a certain reference value, I believe that you read this javascript event monitoring and event delegation how to achieve the article will have a harvest, let's take a look.

Event monitoring and event delegation

In js, element.addEventListener () is often used to listen for events. However, this approach can have a performance impact when there are a large number of elements on the page that need to bind events. At this point, we can monitor the event in the way of event delegation.

Each event goes through three stages.

Capture

Reach the target

Bubbling

Event delegation needs to use the bubbling of the event, which means that when the event occurs, the upper layer will receive the event layer by layer.

The page structure is as follows:

Button

When the button is clicked, first button receives the event, then bubbles to the upper layer, then id= "div1" receives the event, then id= "div2", all the way to the top of document.

So you can add an event handler to the parent, which receives event information from all child nodes. This is the event delegate.

Performance comparison between event monitoring and event delegation

Compare the performance of event listeners with event delegates by building several button elements and binding event listeners to them.

1. Build several button elements and add them to body

Var body = document.getElementById ('body'); var fragment = document.createDocumentFragment (); for (var I = 0; I < 100; iTunes +) {var btn = document.createElement (' button'); btn.id = I; btn.className = 'btn'; btn.type =' button'; btn.innerText = 'button' fragment.appendChild (btn);} body.appendChild (fragment)

At this point, the page generates 100 buttons with an id of 0 to 99. Class' btn';fragment is a document fragment. The advantage compared to the following code is

For (var I = 0 position I)

Tags: Events delegates monitoring elements performance pages number buttons methods listeners knowledge code content processors that is time articles processing demanding elegant Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Redmi Shulou Tech Info Shulou Technology Apple OPPO Reno