DOM events and event delegates

DOM events

concept

What is the event? Some say “click”, others say “addEeventlistener()”, and others say think of it as a browser-specific property.

All of the above are marginal, but not accurate.

In simple terms, DOM events are moments of interaction between a code document and the browser. The word instant, underline!

grammar
element.addElementListener('events',fn)
Copy the code

Add the event type to the element and then follow it with the function you want to execute.

The W3C will add bool to the end:

When bool is true, listen during the capture phase

If bool is not passed or false, listen during the bubble phase

When does it bubble? What is capture? Next I will introduce them to you!


Event capture and event bubble

Flow of events

Before we talk about capture and bubble, we need to understand what the flow of events looks like.

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>The event model</title>
</head>
<body>
    <div class="Zhang Sanfeng">
        <div class="Zhang Cuishan">
              <div class="Zhang Wuji">Practice Tai Chi together</div>
        </div>
    <div>
</body>
</html>
Copy the code

This is a multilayer HTML block when we attach a **’click’ event to each of the three divs.

When I click “Practice Tai Chi together”, are all three of their FN’s invoked?

Answer: yes, by clicking on the text, you have clicked on all three

What about their call order?

Answer: It can be Zhang Sanfeng -> Zhang Cuishan -> Zhang Wuji; It can also be Zhang Wuji -> Zhang Cuishan -> Zhang Sanfeng

The process of this call is the order in which the page receives the events, also known as the event stream.


Event capture and event bubble

When the call order is zhang Sanfeng -> Zhang Cuishan -> Zhang Wuji, the order of event invocation is from the parent element to the child element, which is event capture

When the call order is zhang Wuji -> Zhang Cuishan -> Zhang Sanfeng, the event call order is from the child element to the parent element, which is called event bubble

The default call order is: Zhang Sanfeng -> Zhang Cuishan -> Zhang Wuji such event capture, of course we can choose the bubble order

If you’re having trouble understanding it, take a look at this:

Here, we can summarize:

An event is divided into three phases:

  • Capture phase

    That is, from Zhang Sanfeng -> Zhang Cuishan -> Zhang Wuji this process from external elements to internal elements to find the listening function

  • The target stage

    That is, it triggers the underlying element to listen to the function. If there is a function, it is called, and if there is no function, it is skipped

  • Bubbling phase

    That is, from Zhang Wuji -> Zhang Cuishan -> Zhang Sanfeng this process from internal elements to external elements to find the listening function

A special case

You have a div that has the same events in the capture phase and the bubble phase. So we write the code for its two phases together:

div.addEventListener('click'.f1) / / the bubbling
div.addEventListener('click'F2,true) / / capture
Copy the code

Which code will execute first, f1 or F2?

Answer: F1 is executed first

In the same level of event execution order, whoever listens first is executed first. If F2 comes first, f2 is executed first

Event delegation

concept

Let’s say you are Li Yunlong, and now you want to train 50 artillery, but you only have 1 Italian gun.

You may choose to designate a squad leader to help you coordinate your training. Of course, you can also choose to assault small devil, get him a 50 Italian guns a person.

If you choose the latter, you can’t say you did wrong, but admire your courage. But in most cases I prefer to entrust the monitor.

This example is very similar to the event delegate when your code looks like this:

<div = 'monitor'>
 <button>Artillery 1</button>
  <button>Artillery 2</button>
   <button>Artillery 3</button>
    <button>Artillery No. 4 /button><button>Artillery 5</button>. <button Artillery 49</button>
       <button>50, artillery</button>
</div>
Copy the code

If you have a cannon (function) for each artillery unit, the memory consumption is particularly high. But if you bind the event to the parent element, that is, delegate to the div, and then execute the event to match the target element, it’s much easier.

example

Suppose we have HTML code like this:

<! DOCTYPEhtml>
<html>
<head>
  <meta charset="utf-8">
  <title>Cloud Dragon Italian gun training program</title>
</head>
<body>
  <div id="admiral">
    <button>solider 1</button>
    <button>solider 2</button>
    <button>solider 3</button>
    <button>solider 4</button>
    <button>solider 5</button>
    <button>solider 6</button>
    <button>solider 7</button>.<button>solider 49</button>
    <button>solider 50</button>
  </div>
</body>
</html>
Copy the code

If you set a tap event for each button, the memory consumption is too high (think how many devils Li yunlong had to kill to fit an Italian gun for each artillery).

The good news is that we can put the listener event on the parent element of the div to tell when the user is listening on the element. It’s as if you could assign a squad leader who knows a lot about training to 50 artillerymen, and have him supervise the training, and train whichever one he wants to train.

Without further ado, let’s get started!

First we bind the listen event to the div (equivalent to assigning a squad leader to an artillery unit).

admiral.addEventListener('click'.(e) = >{})// Bind the event to the parent element #admiral
Copy the code

Next, we need to give the parent the right to listen on these children.

admiral.addEventListener('click'.(e) = >{
    const t = e.target  
    if(t.tagName.toLowerCase() === 'button') {console.log(t.textContent+'Trained by roll Call')
  // If the clicked label is button, then the function takes effect}})// Bind the event to the parent element admiral
Copy the code

So which button you click on will do the corresponding thing.

This is how simple and useful event delegation is.

If you still don’t understand it, it doesn’t matter. You can straighten it out by tapping it several times yourself.