JS in the event delegate or event agent detailed __js

Source: Internet
Author: User

Cause:

1, this is the classic type of interview, to find work of the small partners to see whether it is helpful;

2, in fact, I have not been clear, write this one is for the memo, the second is to other know it is not known why the small partners to refer to;

Overview:

What do you call an event commission? It also has a name called the event agent, JavaScript Advanced Programming: The event delegate is the use of event bubbling, only specify an event handler, you can manage a type of all events. What does that mean, then? On the Internet, Daniel and I have basically used the same example to talk about the event delegates, is to take express to explain this phenomenon, I carefully think about it, this example is really appropriate, I do not think of other examples to explain, jiehuaxianfo, I picked, we seriously understand what the event commissioned in the end is a principle:

Three colleagues are expected to receive a courier in Monday. For the express delivery, there are two ways: one is three people in the company doorway and other express delivery, the second is entrusted to the front desk mm on behalf of the sign. In reality, most of us adopt the commissioned program (the company will not tolerate so many employees standing at the door in order to wait for Express). Reception mm after receiving the courier, she will determine who the recipient is, and then according to the recipient's request for signature, or even on behalf of the payment. This scheme also has an advantage, that is, even if the company's new employees (no matter how much), the receptionist will be sent to the new staff after The courier verification and on behalf of the sign.

There are actually 2 layers of meaning here:

First, now entrusted to the front desk colleagues can be signed on behalf of the program, the existing DOM node is an event;

Second, the new staff can also be reception mm on behalf of the signing, that is, the new program added DOM node is also an event.

Why would you use an event delegate:

Generally speaking, Dom needs to have an event handler, we will directly set the event handler for it, if it is a lot of DOM need to add event processing. For example, we have 100 Li, each Li has the same click event, maybe we use the For loop method to traverse all of the Li, and then add events to them, so what will be the effect of doing so.

In JavaScript, the number of event handlers added to the page is directly related to the overall performance of the page, because the more times you need to interact with the DOM nodes, the greater the number of accesses to the DOM, and the more times the browser will redraw and rearrange, the longer the interactive readiness of the entire page. This is why performance optimization is one of the main ideas to reduce the reason for DOM operations, if you want to use event delegation, will put all the operations in the JS program, and the operation of the DOM only need to interact once, so that can greatly reduce the number of interactions with the DOM, improve performance;

Each function is an object, and an object takes up memory, the more objects, the greater the memory occupancy rate, the less natural performance (memory is not enough, is a mishap, haha), such as the above 100 Li, will occupy 100 memory space, if it is 1000, 10,000, it can only say hehe, If you use an event delegate, then we can only operate on its parent (if there is only one parent), so that we need a memory space is enough to save a lot of natural performance will be better.

The principle of the event delegate:

Event delegates are implemented using the bubbling principle of events, and what is event bubbling? That is, the event starts at the deepest node and then propagates the event up and down, for example: There is a node tree on the page,div>ul>li>a; such as a click event for the innermost one, then the event will be performed on a layer-by-level a> Li>ul>div, there is such a mechanism, then we give the most outer div plus click event, then inside the Ul,li,a do click event, will bubble to the outermost div, so will trigger, this is the event delegate, delegate them to execute the event on behalf of their parent.

How event delegates are implemented:

Finally to the core of this article, Haha, before introducing the method of event delegation, let's look at an example of a general method:

Child nodes implement the same functionality:

<ul id= "UL1" >
    <li>111</li>
    <li>222</li>
    <li>333</li>
    <li>444</li>
</ul>

The realization function is to click on Li, Pop 123:

Window.onload = function () {
    var Oul = document.getElementById ("Ul1");
    var aLi = oul.getelementsbytagname (' li ');
    for (Var i=0;i<ali.length;i++) {
        Ali[i].onclick = function () {
            alert (123);
        }
    }
}

The code above means very simple, believe that a lot of people are so realized, we see how many times the DOM operation, first to find UL, and then Traverse Li, and then click Li, but also find a target Li's position, in order to perform the final operation, each click to find Li;

So what happens when we do it in the way that the event is commissioned?

Window.onload = function () {
    var Oul = document.getElementById ("Ul1");
   Oul.onclick = function () {
        alert (123);
    }
}

Here with the parent UL do event processing, when Li is clicked, because of bubbling principle, the event will bubble to UL, because there are clicks on the UL event, so the event will trigger, of course, here when you click on the UL, it will trigger, then the problem comes, If I want the effect of the event agent to be the same as the event effect directly to the node, for example, only click Li to trigger, not afraid, we have the trick:

The event object provides a property called Target that can return the target node of the event, we become the event source, that is, Target can represent the DOM for the current event operation, but it is not really manipulating the DOM, of course, this is compatible, The standard browser uses the Ev.target,ie browser to use the event.srcelement, at this time only then obtains the current node the position, does not know is what node name, here we use nodename to obtain specifically what label name, this return is a capitalization, we need to turn lowercase to compare (the custom question):

Window.onload = function () {
var Oul = document.getElementById ("Ul1");
Oul.onclick = function (EV) {
var ev = EV | | window.event;
var target = Ev.target | | Ev.srcelement;
if (target.nodeName.toLowerCase () = = ' Li ') {
alert (123);
alert (target.innerhtml);
}
}
}

This change only click Li will trigger the event, and only one time DOM operation, if the number of Li, will greatly reduce the operation of the DOM, optimized performance can be imagined.

The above example is said that Li operates the same effect, if each Li is clicked the effect is different, then use the event delegate also useful.

<div id= "box" >
        <input type= "button" id= "Add" value= "Add"/> <input type=
        "button" id= "Remove" value= "Delete"/>
        <input type= "button" id= "Move" value= "mobile"/> <input "
        button" type= "select" id= "Select"/>
    </div>
Window.onload = function () {
            var add = document.getElementById ("add");
            var Remove = document.getElementById ("Remove");
            var move = document.getElementById (' move ');
            var Select = document.getElementById ("select");
            
            Add.onclick = function () {
                alert (' Add ');
            Remove.onclick = function () {
                alert (' delete ');
            Move.onclick = function () {
                alert (' move ');
            Select.onclick = function () {
                alert (' select ');
            }
            
        }

The effect of the above I will not say more, very simple, 4 buttons, click on each one to do different operations, then at least 4 times DOM operation, if the event commissioned, can be optimized.

Window.onload = function () {
            var obox = document.getElementById ("box");
            Obox.onclick = function (ev) {
                var ev = EV | | window.event;
                var target = Ev.target | | ev.srcelement;
                if (target.nodeName.toLocaleLowerCase () = = ' input ') {
                    switch (target.id) {case ' add '
                        :
                            alert (' Add ');
                            break;
                        Case ' Remove ':
                            alert (' delete ');
                            break;
                        Case ' moves ':
                            alert (' move ');
                            break;
                        Case ' SELECT ':
                            alert (' select ');
                            Break;}}}
            
        

With event delegates, you can accomplish all the effects with just one DOM operation, which is definitely better than the performance above.

Now it's all about the operations under the existing DOM node that the document loads, so if it's the new node, does the new node have an event? In other words, a new employee is coming, he can receive the courier.

Look at the normal way to add a node:

<input type= "button" name= "" id= "btn" value

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.