This is the 10th day of my participation in Gwen Challenge

Event is an important knowledge point of JS Web API. We usually see the web page, Ken more content to use events. For example, a click, a drop down, a scroll, all use events.

1. Event binding

What happens when an event is bound to an event?

Events are human actions that can be captured by JS. So what is human manipulation? For example, mouse clicking, dragging, zooming and so on, and after these actions are captured by JS, are events.

Here’s an example:

For example, I now want to go downstairs to shout to give up the aunt to help me open an entrance guard, then the operation of this shout is an event, equivalent to Shouting a function to work in JS.

With events out of the way, let’s talk about event binding.

What is javascript event binding?

Continue with the example above. Yelling is an event, so how do I do it? I need to do a binding on my action. I can bind a function that solves the problem of how I call it. For example, if I want to go downstairs to shout, then this function says that I need to go downstairs to shout.

Therefore, event binding can be understood as: on the premise of a triggering event, followed by an event handler function, which contains the specific process of the action to be executed, which is called event binding.

Next we write an event binding procedure in code.

function bindEvent(elem, type, fn){
    elem.addEventListener(type, fn);
}

const btn1 = document.getElementById('btn1');
bindEvent( btn1 , 'click'.event= > {
    console.log(event.target); //event.target is the element that gets triggered
    event.preventDefault(); // Prevent default behavior
    alert('clicked');
});
Copy the code

The following information is displayed.

And you can see that by clicking on the button event, you get the element that’s triggered, and that’s an event binding.

2. How are events implemented?

Events are publish-subscribe based, meaning that the event-related code is read when the browser loads, but not executed until a specific event is triggered.

For example, clicking a button is an Event, and the piece of code responsible for handling the Event is often called an Event Handler, which is the action of “initiating the display of the dialog box.”

On the Web side, we often see DOM events:

  • DOM0 level eventsTo bind directly to HTML elementson-event, such asonclickIf you cancel it,dom.onclick = nullThere can only be one handler for an eventThe back will cover the front.
  • Grade DOM2 eventsThrough theaddEventListenerRegistered event, passedremoveEventListenerTo delete the event,An event can have more than one event handler, in order, capturing events and bubbling events.
  • Level the DOM3 event, added event types, such asUIEvent, focus event, mouse event.
    • UI events, which are triggered when the user interacts with elements on the interface.
    • Focus events, which fire when focus is gained or lost with an element.
    • Mouse events that are triggered when the user performs an action on the page using the mouse.

Two, the event bubbling

1. Event model

The DOM event flow defined by W3C occurs in three stages: capturing, targetin, and bubbling.

  • Bubble events: When you use event bubbles, child elements fire first and parent elements fire later.
  • Capture events: When you use event capture, the parent element fires first and the child element fires later.

2. Event model analysis

We use the W3C standard DOM event flow model diagram to look at event capture, event bubbling, and DOM event flow.

As you can see from the figure, the element event response in the DOM tree starts from the top-level Window, flows to the target element (2), and then flows from the target element to the top-level Window.

In general, we divide this event flow into (1) capture phase, (2) target phase, and (3) bubbling phase. -> Serial number Corresponds to the number in the figure

(1) Capture stage

In the capture phase, the event response starts from the outermost Window and progresses from layer to layer until it reaches the specific event target element, as shown in the figure (1). Also in the capture phase, bubbling events that respond to element registration are not handled.

(2) Target stage

The target phase refers to the lowest element that triggers the event, as shown in figure 2.

(3) Bubbling stage

The bubbling stage is contrary to the capture stage. The response of the event is transmitted from the bottom layer to the outermost Window layer by layer, that is, bubbling up layer by layer, as shown in (3) above.

AddEventListener syntax

We now know that the three stages of DOM event flow are the capture phase, then the target phase, and finally the bubbling phase. This is the reason why we usually see some interview questions that say capture first and then bubble. At this point, you should have a clear understanding of the DOM event flow.

In practice, we can set an element’s event model with the element.addeventListener () function, which can be set to bubble events or capture events.

Let’s look at the basic syntax of the addEventListener function:

element.addEventListener(type, listener, useCapture);
Copy the code

The three parameters are as follows:

Type: string of the listening event type.

Listener: The callback function that the event listens on, that is, the function to be processed after the event is triggered.

UseCapture: The default value is false, indicating that the event bubbles. When set to true, event capture.

4. Event bubbling and event capturing examples

Let’s use a few examples of event bubbling and event capturing.

(1) Event bubbling

I’ll start with some code.

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <title>Document</title>
</head>
<style>
    #a{
        background-color: darkcyan;
        line-height: 40px;
        color: cornsilk;
    }
    #b{
        background-color: chocolate;
    }
    #c{
        background-color: cornflowerblue;
    }
</style>
<body>
    
    <div id="a">Event a<div id="b">Event b<div id="c">Event c</div>
        </div>
    </div>

    <script>
        let a = document.getElementById('a');
        let b = document.getElementById('b');
        let c = document.getElementById('c');

        // Register the bubbling event listener
        a.addEventListener('click'.() = > {console.log("A" bubble.)});
        b.addEventListener('click'.() = > {console.log('b' bubble.)});
        c.addEventListener('click'.() = > {console.log("C" bubble.)});
    </script>
</body>
</html>
Copy the code

When we click on event C, the browser executes as follows:

As expected, bubbles bubble from bottom to top, so the final execution order is event C → Event B → Event A, printing bubbles C → bubble B → bubble A.

(2) Event capture

I’ll start with some code.

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <title>Document</title>
</head>
<style>
    #a{
        background-color: darkcyan;
        line-height: 40px;
        color: cornsilk;
    }
    #b{
        background-color: chocolate;
    }
    #c{
        background-color: cornflowerblue;
    }
</style>
<body>
    
    <div id="a">Event a<div id="b">Event b<div id="c">Event c</div>
        </div>
    </div>

    <script>
        let a = document.getElementById('a');
        let b = document.getElementById('b');
        let c = document.getElementById('c');

        // Register the capture event listener
        a.addEventListener('click'.() = > {console.log("To capture a")}, true);
        b.addEventListener('click'.() = > {console.log('capture b')}, true);
        c.addEventListener('click'.() = > {console.log("Capture c")}, true);
    </script>
</body>
</html>
Copy the code

At this point, we add true to the addEventListener, so when we click on event C, the browser executes the following:

As expected, capture is captured from the top down, that is, from the outer layer to the inner layer, so the final execution sequence is event A → Event B → Event C, printing capture A → capture B → capture C.

(3) Event capture VS event bubbling

Next, we register capture and bubble events for all three elements of the code event ABC above, and take event C as the trigger event body, that is, event C as the target phase in the event flow.

Attach a code.

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta  name="viewport" content="width=device-width, < span style> #a{background-color: darkcyan; background-color: darkcyan; line-height: 40px; color: cornsilk; } #b{ background-color: chocolate; } #c{ background-color: cornflowerblue; } < / style > < body > < div id = "a" > event a < div id = "b" > event b c < div id = "c" > events < / div > < / div > < / div > < script > let a = document.getElementById('a'); let b = document.getElementById('b'); let c = document.getElementById('c'); A.addeventlistener ('click', () => {console.log(" bubble a")}); B.a ddEventListener (' click ', () = > {the console. The log (' bubble b ')}); C.a. ddEventListener (' click ', () = > {the console. The log (" bubbling c ")}); A.addeventlistener ('click', () => {console.log(" catch a")}, true); B.a ddEventListener (' click ', () = > {the console. The log (' capture b ')}, true); C.a. ddEventListener (' click ', () = > {the console. The log (" c "capture)}, true); </script> </body> </html>Copy the code

When we click on event C, the browser executes as follows:

As expected, events are captured and bubbled later. When captured, events are captured from the outside in, so the print is bubbling capture A → capture B → capture C. When bubbling, events bubble from the inside out, so the final print is bubbling C → bubbling B → bubbling A.

Iii. Event Agent (Event Entrustment)

Having covered event bubbling and event brokers, it is now easier to understand event brokers.

Event broker, that is, event delegate. Event broker binds a series of inner element events to outer elements using event bubbling or event capture.

Let’s look at an example.

<ul id="item-list">
    <li>item 1</li>
    <li>item 2</li>
    <li>item 3</li>
    <li>item 4</li>
</ul>
Copy the code

For example, we want to bind events to each li element below the UL list. If we had done it the traditional way, we would have unbound them one by one. It might be fine when you have a small amount of data, but what about when you have a large amount of data? Binding them one by one is horrible.

Hence the event broker. By using the event broker, we can change an operation that binds multiple events into one that binds only once, which greatly reduces code duplication.

Therefore, event bubbling or event capture is used to achieve the effect of event broker. The specific implementation is as follows:

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <title>Document</title>
</head>
<body>
   <ul id="item-list">
        <li>item 1</li>
        <li>item 2</li>
        <li>item 3</li>
        <li>item 4</li>
    </ul>
    <script>
        let items = document.getElementById('item-list');
        // Implement event broker through event bubbling
        items.addEventListener('click'.(e) = > {console.log('Bubble: click',e.target.innerHTML)}, false);
        // Implement event broker through event capture
        items.addEventListener('click'.(e) = > {console.log('Capture: click',e.target.innerHTML)}, true);
    </script>
</body>
</html>
Copy the code

When an item in the list is clicked, the result is as follows:

As you can see from the figure above, when the target element is clicked, it can be captured, and when the capture is finished, it can be bubbled, and the effect of clicking on the current element only shows the current element.

In the meantime, the observant reader has noticed that in our code above, the order of writing is bubble first and capture later. But the result print is still capture and bubble. This is consistent with what we said above about the sequence of DOM event streams, which are captured and then bubbled, regardless of the actual code order.

Iv. Summary and review

Having covered event binding, event bubbling and event capture in the DOM event flow model, and event brokers, let’s conclude and review.

(1) The above content is summarized as follows:

  • The DOM event flow has three phases: capture phase, target phase, and bubble phase. The three stages are as follows: capture stage → target stage → bubbling stage.

  • For both target phase and non-target phase elements, the order of event response execution follows the principle of capture before bubble.

    Note: Target stage is the current click event, namely the target stage. The non-target stage is the event affected by the periphery.

  • Event capture is performed layer by layer from the top layer of Windows, while event bubbling is the opposite.

  • Event broker (that is, event delegate) is implemented according to the mechanism of event bubbling or event capturing.

(2) Use several topics to review the knowledge points we have talked about above

Q1: Describes the process of event bubbling

A1:

  • Based on DOM tree structure
  • Events will rise, layer by layer, up the triggered element
  • Application scenario: Event proxy

Q2: How do I listen for clicks on each image when I pull down an infinite list of images?

A2:

  • Handle with an event broker
  • Get the trigger element with e.target
  • Matches is used to determine whether the element fires

V. Concluding remarks

It was never quite clear why the event was captured and then bubbled up, I had no general framework in my head, and I couldn’t make sense of it in the literal sense. Until I looked at the W3C diagram of the DOM event flow model, I suddenly understood why events were captured and then bubbled up. Because the Window object is directed to the user, when the user fires an event, such as a click event, it must start with the Window object and work its way up through the layers. So it’s natural to catch and then bubble!

So much for events in the Web API! If you have any questions, please leave a message in the comment area or send a private message to me

  • Pay close attention to the public number Monday lab, irregularly share learning dry goods, more interesting columns to unlock you ~

  • If this article is useful to you, be sure to like it and follow it