编程知识 cdmana.com

What is the event agent of the browser DOM element

event

In the web page , If you want to engage with users “ Interaction ”, There has to be some way to know what he's done . Of course , Browser developers have long been based on W3C Event specification The underlying logic is implemented , We just need to pass Web API Medium DOM Event, Register what you want to listen to DOM Event listeners for elements and events (Event Listener) You can easily master the user's every move on the web page .

Event monitoring

We can monitor events in the DOM Through the element addEventListener Register listener . for example :

document.querySelector('#id').addEventListener('click', clickHandler)

When you click #id Element will trigger clickHandler And pass in an event , Its content contains the necessary data in the process of event transmission , For example, the target element 、 The current element 、 The delivery phase and so on . Then we can get the data we need from it , And do what you want to do with that data .

There's a lot of interaction on the web right now , If you listen to events one by one to write , Except for poor performance , It's hard to write ; At this point, it shows “ Event agent ” The importance of !

But before we talk about event agents , Now we need to understand DOM Tree What's the mechanism of time transfer on

Time transmission

You can refer to W3C Defined by the Event Flow chart :

image.png

The specification defines three stages of time transfer :

  • Capture phase : from DOM Tree In turn, the root node of the , In the process, the capture phase event listening of each element is triggered .
  • Target stage : Reach the event target (Event Target), Trigger event monitoring according to the registration order .
  • bubbling phase : From the event target to the outside in order , In the procedure, the bubbling phase event monitoring of each element is triggered .

As shown in the figure , When the user triggers a DOM Element event , First of all Capture phase (Capture Phase), From the root node to the event target step by step ; When you reach the target, you enter Target stage (Target Phase), And then it starts turning back , Enter the... Passed to the root node bubbling phase (Bubbling Phase).

In the use of addEventListener When registering event listeners , You can pass a third parameter , Specifies the stage at which this event listening is to be triggered :

elem.addEventListener('click', eventHandler) //  Not specified , The default is bubble 
elem.addEventListener('click', eventHandler, false) //  Bubbling 
elem.addEventListener('click', eventHandler, true) //  Capture 
elem.addEventListener('click', eventHandler, {
  capture: true //  Whether it's capture . IE、Edge  I won't support it . For other properties, please refer to  MDN
})

By simply passing back and forth , So we can control the trigger time more precisely !

Event agent

Now we're finally talking about the event agent . Because of the mechanism of event passing , The event of a child element is bound to pass through its parent element in the transmission process ; And the event agent , As the name implies, the child element event listener is handed over to the parent element agent .

What does that mean ? Let's go straight to a simple control example :

First of all HTML skeleton :

<button id="push">push</button>
<button id="pop">pop</button>

<ul id="list"></ul>

No event agent

(function() {
  document.querySelector('#push').addEventListener('click', pushHandler)
  document.querySelector('#pop').addEventListener('click', popHandler)

  const list = document.querySelector('#list')

  function pushHandler() {
    list.appendChild(getNewElem(list.childNodes.length))
  }

  function popHandler() {
    document.querySelectorAll('#list>li')[list.childNodes.length - 1].remove()
  }

  function getNewElem(text) {
    const elem = document.createElement('li')
    elem.innerText = text
    elem.addEventListener('click', eventHandler)
    return elem
  }
  
  function eventHandler(e) {
    alert(e.target.innerText)
  }
})()

There's an event agent

(function() {
  document.querySelector('#push').addEventListener('click', pushHandler)
  document.querySelector('#pop').addEventListener('click', popHandler)

  const list = document.querySelector('#list')
  
  list.addEventListener('click', listClickHandler)
  
  function pushHandler() {
    list.appendChild(getNewElem(list.childNodes.length))
  }

  function popHandler() {
    document.querySelectorAll('#list>li')[list.childNodes.length - 1].remove()
  }

  function getNewElem(text) {
    const elem = document.createElement('li')
    elem.innerText = text
    return elem
  }
  
  function listClickHandler(e){
    if (e.target.tagName === 'LI') alert(e.target.innerText)
  }
})()

The difference is in the target element of event listening

In the version without event agents, each li Event listeners are registered on , As the number increases, browsers have more and more listeners , It has a great influence on performance ; On the other hand, in versions with event proxies , The event listener is registered in the outer layer of ul On , No matter how much content , The browser only needs to bear the consumption of a set of event listeners .

Event handling in libraries and frameworks

stay DOM This part of event handling ,jQuery and Vue Both encapsulate native event listeners , It's convenient for us to quickly set up 、 Use , It will even automatically remove useless event monitoring for you .

But in React in ,React DOM Event listeners registered directly on , Actually, it's listening React Extra encapsulated React DOM Event, And proxy all events to document On , It's very different from a native event ; Especially if you mix React DOM Even tListener And native addEventListener, The order of execution between event listeners is likely to be inconsistent with expectations , Writing React Pay special attention to .

If you are interested in further research, you can do it in React Source code Find the code section about event handling in .

173382ede7319973.gif


This article first send WeChat messages public number : Front end pioneer
Welcome to scan the two-dimensional code to pay attention to the official account. , I push you fresh front-end technical articles every day

 Welcome to scan the two-dimensional code to pay attention to the official account. , I push you fresh front-end technical articles every day

Welcome to the rest of this column :


版权声明
本文为[Crazy technology house]所创,转载请带上原文链接,感谢

Scroll to Top