JavaScript event proxy and delegated instance Analysis _ javascript skills

Source: Internet
Author: User
The term delegate often appears in javasript, which indicates the meaning of the word, proxy, and delegation. Delegate interfaces are also frequently seen in various frameworks. What are the special usage of these interfaces? This article mainly introduces the usage and principle of javascriptdelegate through examples. In JavaScript, we often encounter the scenario of listening to multiple li entries in the list. Suppose we have a list as follows:

The code is as follows:



  • Item1

  • Item2

  • Item3

  • Item4


If we want to implement the following functions: When you click a li, alert outputs the li content, which is usually written as follows:

When there are few items in the list, add an onclick event to each li directly.
When there are many list items, the listener is called for each list item during onload.
The first method is simple and straightforward, but does not take into account the separation of html and JavaScript. it is not recommended to use it. the code for the second method is as follows:

The code is as follows:


Window. onload = function (){
Var ulNode = document. getElementById ("list ");
Var liNodes = ulNode. childNodes | ulNode. children;
For (var I = 0; I LiNodes [I]. addEventListener ('click', function (e ){
Alert(e.tar get. innerHTML );
}, False );
}
}

As can be seen from the above, if the li is deleted or added, the function () must be constantly changed and error-prone. Therefore, we recommend that you use event proxy before using event proxy, let's take a look at event phase ):

Event phase:

When a DOM Event is triggered, it does not trigger only once on its origin object, but goes through three different stages. In short, an event first flows from the root node of the document to the target object (capture phase), and is then triggered (target phase) on the target peer ), back to the root node of the document (bubble stage) (picture from W3C ):

Capture Phase)

The first phase of an event is the capture phase. Events start from the root node of the document and flow to the target node of the event with the structure of the DOM tree. On the way, the DOM node passes through various levels, and the capture event is triggered on each node until the target node reaches the time. The main task of the capture phase is the resume propagation path. in the bubble phase, the time will be traced back to the document root node through this path.

The code is as follows:


Element. removeEventListener (& ltevent-name>, , );

We use the above function to set a listener for the node. you can set the listener callback function to true to add a listener for the event capture phase. In practical applications, we do not have many use cases for monitoring in the capture phase. However, by processing events in the capture phase, we can prevent similar click events from being triggered on a specific element.

The code is as follows:


Var form = document. querySeletor ('form ');
Form. addEventListener ('click', function (e ){
E. stopPropagation ();
}, True );

If you are not familiar with this usage, you 'd better set it to false or undefined to listen to the event in the bubble stage.

Target Phase)

When an event arrives at the target node, the event enters the target stage. The event is triggered on the target node, and then reversely returns to know that the event is propagated to the outermost document node.

For multi-layer nested nodes, mouse and pointer events are often located on the innermost layer of elements. Assume that you have set the click listening function on a p element, and the user clicks on the p element inside the p element, then the p element is the target element of the time. Event bubbling allows us to listen to the click event on the p or upper-level element, and trigger the callback function during time propagation.

Bubble Phase)

After an event is triggered on a target event, it is not terminated on this element. It bubbles up with the DOM tree until it reaches the root node of the outermost layer. That is to say, the same event will be triggered once on the parent node of the target node, the parent node of the parent node... until the node on the outermost layer.

Most events are bubbling, but not all. Details: Specifications

From above, we can think of using event proxy to listen to every li. The code is as follows:

The code is as follows:


Window. onload = function (){
Var ulNode = document. getElementById ("list ");
UlNode. addEventListener ('click', function (e ){
If(e.target&e.tar get. nodeName. toUpperCase () = "LI") {/* determine whether the target event is li */
Alert(e.tar get. innerHTML );
}
}, False );
};

The above is all the content in this article, hoping to be helpful to everyone who is familiar with the delegate and proxy of javascript events.

Please take a moment to share your article with your friends or leave a comment. Thank you for your support!

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.