HTML Event (iii) event flow and event delegation

Source: Internet
Author: User

This article focuses on event flow and event delegation in the HTML DOM.

Other event Articles

1. Introduction to the HTML event (i) event

2. HTML Event (ii) registration and logoff of events

3. HTML event (c) Event flow and event delegation

4. HTML event (quad) analog event action [unpublished]

Directory

1. Event Flow

1.1 What is an event stream

1.2 Three stages of event flow

1.3 AddEventListener () registering the event stream stage

1.4 Preventing propagation of event streams

2. Event Delegation

2.1 What is an event delegate

2.2 ul, Li scene Example

2.3 JQuery's event delegate

2.3.1 Delegate ()

2.3.2 on ()

1. Event Flow 1.1 What is the event flow

In short, the elements of HTML will have nested relationships, such as: a div nested a button buttons, when 2 elements are registered click Click event. When you click the button inside the div, the Click event is also triggered.

So the question comes, since it all triggers, is there a trigger order? Are they triggered in such a sequence as Div→button, or in the order of Button→div?

Previously, both browser makers Netscape and Microsoft had their own sequence of triggers:

Netscape's browsers are captured in such a way that they are triggered in the order of Div→button.

and Microsoft's browser uses the bubbling way : triggers in the order of Button→div.

In the 2-level DOM event specification, simply merge: The event stream contains these 2 stages.

1.2 Three stages of event flow 1.2.13 Stages

The 2-level DOM event specification has three stages of the event flow: The capture phase , the target stage , and the bubbling phase :

Capture Phase (Capture Phase): A stage in which events are triggered sequentially from the outermost window object to the parent node of the target node. (from outside to inside)

Target Stage (target Phase): The stage when the event is triggered on the target node .

Bubbling Stage (bubbing Phase): The stage in which events are triggered sequentially from the parent node of the target node to the outermost window object. (from inside to outside)

1.2.2 Example Diagram

1.3 AddEventListener () registering the event stream stage

When an element object registers an event through AddEventListener(), the third parameter of this method can set whether this registration is a capture or bubbling phase .

1.3.1 AddEventListener () method description

Syntax : Eventtarget.addeventlistener (EventName, EventHandler [, Usecapture])

Parameters :

①eventname {string}: The name of the event to register is not case-sensitive. This name does not need to be prefixed with "on" asthe event property is registered. such as registering a mouse click event, write as Click.

②eventhandler {function | object}: Functions or Function objects. The function to execute when the event is triggered, and when the same event is registered multiple times using a function object, register it again.

③usecapture {Boolean} optional: is in the capture phase and defaults to false.

|-true: The currently registered event is the capture phase.

|-false: The currently registered event is not a capture phase, for the bubbling phase.

1.3.2 Example

The example uses some of the properties of the event events object:

ReadOnly Object currenttarget : Read-only to get the object that is handling this event.

readonly int eventphase : Read-only, which represents the processing phase of an event: 0 indicates that no processing is being processed, 1 represents the capture phase, 2 represents the target stage, and 3 represents the bubbling phase.

ReadOnly Object target : Read-only to get the objects that triggered this event.

function Clickhandle (e) {    Console.log ("Event stage:" +e.eventphase+ '; Target: ' +e.target+ '; Currenttarget: ' + E.currenttarget)} window.addeventlistener (' Click ', Clickhandle,false); Window.addeventlistener (' Click ', Clickhandle,true);d ocument.addeventlistener (' click ', Clickhandle,false);d ocument.addeventlistener (' click ', Clickhandle,true);d ocument.documentElement.addEventListener (' click ', Clickhandle,false); Document.documentElement.addEventListener (' click ', Clickhandle,true);d ocument.body.addEventListener (' click ', Clickhandle,false);d ocument.body.addEventListener (' click ', Clickhandle,true);d Ocument.getelementbyid (' div '). AddEventListener (' click ', Clickhandle,false);d Ocument.getelementbyid (' div '). AddEventListener (' click ', Clickhandle,true);d Ocument.getelementbyid (' btn '). AddEventListener (' click ', Clickhandle,false); document.getElementById (' btn '). AddEventListener (' click ', Clickhandle,true);

1.4 Preventing propagation of event streams

The stoppropagation(),stopimmediatepropagation() method of the event events object prevents subsequent propagation of the event stream.

Note : Thestopimmediatepropagation() method, in addition to blocking event flow propagation, also blocks subsequent event handlers for this element in the current event.

The three stages of the event flow call these 2 methods, and there are different ways to block propagation:

1.4.1 called in the capture phase

Description : When the stoppropagation() method is called during the capture phase, subsequent event streams for this element are blocked, including the capture phase, the target stage, and the bubbling phase .

Example : Call this method in the BODY element capture phase in the 1.3.2 sample code

Document.body.addEventListener (' click ', Function (e) {    Console.log ("Event stage:" +e.eventphase+ '; Target: ' +e.target+ ') ; Currenttarget: ' +e.currenttarget)    e.stoppropagation ();},true);

result : The event flow is at the capture stage of the body and no subsequent stages are executed

1.4.2 called in the target phase

Description : When the Stoppropagation () method is called in the target segment, the capture and target phases are executed and the bubbling phase is not executed .

Example : Call this method in the target phase of the button element in the 1.3.2 sample code

document.getElementById (' btn '). AddEventListener (' click ', Function (e) {    console.log ("Capture Phase registration: Event Stage:" + E.eventphase+ '; Target: ' +e.target+ '; currenttarget: ' +e.currenttarget '    e.stoppropagation ();},false); document.getElementById (' btn '). AddEventListener (' click ', Function (e) {    console.log ("Bubble Stage Registration: Event Stage:" + E.eventphase+ '; Target: ' +e.target+ '; currenttarget: ' +e.currenttarget '    e.stoppropagation ();},true);

result : The capture phase and the target phase are completed and the bubbling phase is not executed.

1.4.3 Call in bubbling phase

Description : When calling the stoppropagation() method in the bubbling segment, the capture and target phases are executed, and the subsequent bubbling phase of the element is not executed .

Example : Call this method in the body bubbling phase of the 1.3.2 sample code

Document.body.addEventListener (' click ', Function (e) {    Console.log ("Event stage:" +e.eventphase+ '; Target: ' +e.target+ ') ; Currenttarget: ' +e.currenttarget)    e.stoppropagation ();},false);

result : The capture phase and the target phase are complete and the body's subsequent bubbling phase is not executed

2. Event Delegate 2.1 What is an event delegate

HTML elements contain nested relationships, and event flows contain bubbling stages. The triggering event of a child element bubbles to the same event on the parent element.

In general, you only need to register a specific event handler for a child element, but what if the child element is too large or frequent to add or subtract?

For example, a UL contains dozens of LI elements, and a separate event registration for each Li element can affect performance. now, as long as the event listener is registered in the parent element, wait for the bubbling phase after the Li event is triggered.

simply put, an event delegate is a bubbling event that the parent element listens on a child element .

2.2 ul, Li scene Example

The div container contains multiple Li child elements and registers the event delegate in the Div container.

HTML code :

<div id= "div" >    <ul id= "ul" >        <li data-key= "Beijing" > Beijing </li>        <li data-key= "Shanghai" > Shanghai </li>        <li data-key= "Hangzhou" > Hangzhou </li>    </ul></div>

JS Code :

document.getElementById (' div '). AddEventListener (' click ', Function (e) {    var value=e.target.attributes[') Data-key '].value; Gets the value of the ' Data-key ' property of the target stage element    Console.log (value);});

  

2.3 JQuery's event delegate

In jquery, the parent element can call delegate (), on () as the event delegate.

2.3.1 Delegate ()

syntax : $ (' parent element '). Delegate (selector [, EventType] [, EventData], handler)

Parameters :

①selector {string}: A child element selector,

②eventtype {eventtype} Optional: Event type triggered. such as: click.

③eventdata {Object} Optional: The value that event.data points to when the event is triggered.

④handler {Function}: handler for event registration.

Example :

$ (' #div '). Delegate (' Li ', ' click ', Function () {    var v = $ (this). Data (' key ');    Console.log (v);});

2.3.2 on ()

Description : At the beginning of the JQuery1.7 version, on () is recommended instead of the delegate () method.

syntax : $ (' element '). On (events [, selector] [, data], handler)

Parameters :

①events {string}: One or more event names.

②selector {string} Optional: child element Selector. Without this value, the event that represents the element registration itself. If this value is included, the registered event is triggered only if the event of the child element is triggered.

③data {Object} Optional: The value that event.data points to when the event is triggered.

④handler {Function}: handler for event registration.

Example :

$ (' #div '). On (' Click ', ' Li ', function (e) {    var v = $ (this). Data (' key ');    Console.log (v);});

  

================================== Series article ==========================================

This article: 5.5 HTML Event (iii) event flow and event delegation

Web Development Road Series articles

HTML Event (iii) event flow and event delegation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.