JavaScript Event Flow

Source: Internet
Author: User
Tags event listener

Abstract : Event Flow This thing is more important, in order to let oneself more understanding of the event stream in JS, must tidy up, comb the event flow of various things ah. Most of this article refers to the third edition of JavaScript advanced programming

Let's start with the original text in a book:

As browsers evolve into the fourth generation (IE4 and Netscape Communicator 4), the browser team encounters an interesting question: which part of the page will have a specific event? Imagine having a set of concentric circles on a piece of paper, if you put your finger on the center of the circle, then your finger is pointing not to a circle, but to a group of circles. The development teams of two companies are consistent in their view of browser events. If you click a button, you also click the button's container element, or even the entire page.

The event flow describes the order in which events are accepted from the page. But interestingly, the IE and Netscape development team actually proposed two diametrically opposed event flow concepts.

1, IE's event flow is the event bubbling stream,

2. The standard browser event stream is the event capture stream.

But Addeventlister gives a third parameter that supports both bubbling and capturing, and the following describes

Event bubbling

The event flow of IE is called event bubbling, which means that the event is propagated as follows: from the specific element of the event, the first level propagates to the less specific node. The cases are as follows:

<!DOCTYPE HTML><HTMLLang= "en"><Head>    <MetaCharSet= "UTF-8">    <title>Event bubbling</title></Head><Body>    <Div>        <P>Point Me</P>    </Div></Body></HTML>

When we click on the P element, the event is propagated like this:

(1) P

(2) Div

(3) Body

(4) HTML

(5) Document

Modern browsers support event bubbling, and IE9, Firefox, Chrome, and Safari keep events bubbling to the Window object.

Event capture

Another stream of events presented by the Netscape team is called event capture. Its principle is just the opposite of event bubbling, which is intended to capture the event before it reaches its intended target, and the most specific node should be the last to receive the event.

For example, in the case above, when the P element is clicked, the propagation direction of the event becomes this:

(1) Document

(2) HTML

(3) Body

(4) Div

(5) P

IE9, Firefox, Chrome, and Safari currently support this event flow model, but some older browsers don't support it, so few use event capture, rather than using event bubbling.

Dom Event Flow

The event flow defined by the "DOM2 level event" consists of three stages: the event capture phase, the target stage, and the event bubbling phase.

The first occurrence of event capture provides an opportunity to intercept the event. Then is the actual target acceptance event. The last stage is the time bubbling phase, in which events can be responded to at this stage. In the previous example, the events are triggered sequentially.

Figure 1-1 (the picture is from the textbook, so there is no P tag for the above case)

In the DOM event stream, the target of the event is not accepted to the event during the capture phase . This means that during the capture phase, the event is stopped from document to P.

The next phase is in the target phase, so the event occurs on P and is considered part of the bubbling phase in event handling . Then, the bubbling phase occurs, and the event is propagated back to document.

Most browsers that support DOM event streams implement a specific behavior, even though the DOM2 level event specification explicitly requires that the capture phase not involve event targets, but IE9, Safari, Chrome, Firefox and Opera9.5 and later will trigger events on event objects during the capture phase. As a result, there are two opportunities to manipulate events on a target object

Event handlers
An event is a user or browser performing some kind of action, such as click, Load, MouseOver.
The function that responds to an event is called an event handler (event listener), and the name of the event handler starts with on, Click=>onclick, Load=>onload

DOM2 provides two ways to let us handle and delete event handlers: AddEventListener () and RemoveEventListener
Btn.addeventlistener (EventType, function () {}, False); The method applies to the DOM node the first argument is the event name the second is the event handler the third is the Boolean value, and True is the event handler that is called for the event capture phase. False to invoke event handlers for the event bubbling phase

Examples of use are as follows:

var btn = document.getElementById (' btn '); Btn.addeventlistener (' click ', Function () {             alert (' event capture ');        }, True); Btn.addeventlistener (' Click ', Function ( {            alert (' event bubbling ');        }, False);

Pop up "event capture" and "event bubbling", the first reaction here is, do they have order?

So I wrote in turn:

  var btn = document.getElementById (' btn ');  Btn.addeventlistener (' click ', Function () {            alert (' event bubbling ');        }, False);  Btn.addeventlistener (' click ', Function () {             alert (' event capture ');        }, True);

Pop up in turn: "Event bubbling" and "event capture"; Go on, down.

This is the way this is written:

<!DOCTYPE HTML><HTMLLang= "en"><Head>    <MetaCharSet= "UTF-8">    <title>Event bubbling</title></Head><Body>    <Div>        <PID= "Parele">I'm the parent element.<spanID= "Sonele">I'm a child element.</span></P>    </Div></Body></HTML><Scripttype= "Text/javascript">varSonele=document.getElementById (' Sonele');varParele=document.getElementById ('Parele');p Arele.addeventlistener ('Click', function() {alert ('Parent-Bubble');}, false);p Arele.addeventlistener ('Click', function() {alert ('Parent-level capture');}, true); Sonele.addeventlistener ('Click', function() {alert ('Sub-bubble');}, false); Sonele.addeventlistener ('Click', function() {alert ('Child capture');}, true);</Script>

When I click "I am Child", the order of pop-up is:"Parent capture"-"sub-bubble"-"subset Capture"-"parent set bubbling";

It can be explained here that when a child element is clicked, the order of execution of the parent is first captured and then bubbled.

To synthesize the preceding code, we can draw a small conclusion:

  When the container element and the nested element, that is, when the event handler is called, the event 捕获阶段 冒泡阶段 executes the event handler in the order of the DOM event stream , which is shown in 1-1

 And when the event is in the target phase, the order of the events is determined by the order in which the binding events are written , as in the above example, the event handlers of the bubbling phase are called first, and then the event handlers in the capture phase are called. Alert out "Subset bubbling", "subset capture" in turn.

Delete an event handler, using RemoveEventListener. Cases:

var btn=document.getelementbyid (' mybtn '); var myfn=function() {    alert (this. id);} Btn.addeventlistener (' click ', MYFN,false); Btn.removeeventlistener (' click ', MYFN,  False);

Note: For maximum compatibility, it is mostly the case that the event handlers are added to the event bubbling phase. Not particularly necessary, it is not recommended to register event handlers during the event capture phase

Compatible with IE browser wording:

IE add and remove event handlers are a little different, so use the following code to do a compatibility deal:

varEventutil ={addHandler:function(el, type, handler) {if(El.addeventlistener) {El.addeventlistener (type, handler,false); } Else{el.attachevent (' On ' +type, handler); }}, RemoveHandler:function(el, type, handler) {if(El.removeeventlistener) {El.removeeventlisterner (type, handler,false); } Else{el.detachevent (' On ' +type, handler); }    }};

The usage is similar to the preceding:

Eventutil.addhandler (' btn ', ' click ', handler);

Event Object

When an event is triggered on the DOM, an event object is generated, with all the information about the event associated with the bread.

The following are some of the more commonly used:

The Currenttarget   event handler is currently processing the element of the event (always equals this) Preventdefault  cancels the event default behavior, such as a linked jump Stoppropagation cancel event bubbling target  The goal of the event

  

Event object compatible with IE:

var eventutil = {addhandler:function (el, type, handler) {if (El.addeventlistener) {El.addeventli        Stener (type, handler, false);        } else if (el.attachevent) {el.attachevent (' on ' + type, handler);        } else {el[' on ' + type] = handler; }}, Removehandler:function (EL, type, handler) {if (El.removeeventlistener) {El.removeeventlis        Terner (type, handler, false);        } else if (el.detachevent) {el.detachevent (' on ' + type, handler);        } else {el[' on ' + type] = NULL;    }}, Getevent:function (e) {return e? e:window.event;    }, Gettarget:function (e) {return e.target? e.target:e.srcelement;        }, Preventdefault:function (e) {if (E.preventdefault) {e.preventdefault ();        } else {e.returnvalue = false; }}, Stoppropagation:function (e) {if (e.stoppropagation) {E.stoPpropagation ();        } else {e.cancelbubble = true; }    }};

Other

The beforeunload of the HTML5 event

Triggered before the page is uninstalled, just like the edit Blog Park article is not saved is a popup prompt box.

The domcontentloaded event of the HTML5 event

Supports adding events before the page is downloaded, without waiting for images, CSS files, or other files to be loaded before they are executed. Allows users to interact with the user as early as possible.

Eventutil.addhandler (document, ' domcontentloaded ',function() {    alert (' I can execute first, haha ')}) 

Event delegate:

Each function is an object, consumes memory, and the more objects in memory, the worse the performance. The solution to too many problems with event handlers is the event delegate.

Event delegation takes advantage of event bubbling to specify only one event handler to manage all events of a certain type. For example:

There are three Li, all need a click event, at this time do not need to give each Li to bind the click event, mainly to his parent UL added a binding event. So click on Li, use bubbling, directly trigger the UL click, just determine which Li's ID

Click. Instead of requiring three Li to bind the click event.

<ul id= "Mylinks" >    <li id= "MyLi1" >text1</li>    <li id= "MyLi2" >text2</li>    <li id= "MyLi3" >text3</li></ul>

A little summary, a mistake, welcome to point out

If you think the article is useful, you can also give a small red packet to encourage encouragement, haha

JavaScript Event Flow

Related Article

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.