Event delegate (the event broker) js the Detailed

This article is reproduced: https://www.cnblogs.com/liugang-vip/p/5616484.html#!comments

js in the event bubbling, the event is entrusted to note some js little knowledge, combined with reprint articles summarize here:

Event bubbling: JS in some events when starting with a bubbling property is to first trigger element to find out whether there is a corresponding registration event, if no longer continue to look to the higher of the parent element if there is a corresponding registration event accordingly, this is event bubbling.

Event delegates: use event bubbling characteristics, this process will be an event on the child element of registration should be registered on the parent element, so that when the child clicks elements found itself without a corresponding event went to look for the parent element accordingly. The advantage of this are: 1 reduction DOM operations and improve performance. 2. You can always add a child element, child element will automatically have the appropriate event handlers.

 

Reprint content of the article:

Due:

1, which is the front end of a classic interview questions, go to work and see a small partner is helpful;

2, in fact, I had never understand, first, to write this memo, and second, to other know not why little friends to reference;

Overview:

What is the event that commissioned it? It also has a named event agency, JavaScript advanced programming terms: event delegate is to use event bubbling, specify only one event handler, you can manage all the events of a certain type. Then what does it mean? Internet Members large cattle speaking event delegate basically use the same example, is to take the courier to explain this phenomenon, I carefully try to figure out a bit, this case really is appropriate, I do not think about other examples to explain, Jiehuaxianfo, I picked up, we seriously understand what event delegate in the end what is a principle:

There are three co-workers expect to receive delivery on Monday. To sign for delivery, there are two ways: First, the three men in front of other courier companies; the second is delegated to sign on behalf of MM foreground. Reality, most of us use of the program commission (the company will not tolerate so many employees just standing in the doorway to wait for delivery). After the front MM received express, she will determine who the recipient, and the recipient accordance with the requirements of the sign, even on behalf of the payment. This approach also has the advantage that even if the company to a new employee (no matter how much), front MM will verify and sign on behalf of employees in the new courier receipt sent.

In fact, here there are two layers of meaning:

First, the front desk is now commissioned colleagues can sign on behalf of that existing dom node program is an event;

Second, new employees also may be sign on behalf of the foreground MM, namely dom-node also has a newly added event.

Why use event delegation:

In general, dom need to have an event handler, we will give it directly to the event handler established like, if it is a lot of dom need to add the event to deal with it? For example, we have 100 li, li each has the same click click event, maybe we will use the method for loop to traverse all li, then add the event to them, what impact do exist?

In JavaScript, added to the number of event handlers on the page will be directly related to the overall operating performance of the page, because the need to constantly interact with the dom node, the more visits dom, causing the browser to redraw the number of rearrangements the more, will be ready to extend the interaction time of the entire page, which is one of the main ideas why the performance optimization is to reduce the causes of DOM operations; If you use event delegation, will put all of the operating procedures js inside, dom operation would only need to interact once, so that we can greatly reduce the number of interactions with the dom and improve performance;

Each function is an object, the object will take up memory is, the more the object, the greater the memory occupancy rate, the worse the performance of natural (not enough memory is flawed, ha), such as above 100 li , will occupy 100 memory space, if it is 1000, 10000 of it, it can only say Oh, and if the event delegate, then we can only its parent (if only one parent) this object operate, so we need a memory space is enough, is not it save a lot of natural performance will be better.

Event commissioned works:

Event delegate is to use the principle of bubbling event to achieve, what is the event bubbling it? That events from the deepest node start, and then gradually spread events up, for example: there is such a node in the tree on the page, div> ul> li> a; for example, to a add a click innermost click event, then this event will will perform out layer by layer, the execution order of a> li> ul> div, there is such a mechanism, then we add to the outermost div click event, then the inside of ul, li, a click event to do that they will bubbling to the outermost div, so will trigger, this is the event delegate, delegate their execution on behalf of the parent event.

Event delegates how to achieve:

And finally to the core of this article, ha ha, before the method of presentation event delegate, let's look at some examples of general methods:

Child nodes to achieve the same functionality:

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

Realize the function by clicking li, pop 123:

Copy the code
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);
        }
    }
}
Copy the code

 The above code simply means, I believe many people are not so implemented, we see how many times dom operation, we must first find ul, li then traversed, then click on the li, when they are looking for a target of li position to perform the last operation, every click to find a li;

So we commissioned to do with the way the event and what will happen?

window.onload = function(){
    var oUl = document.getElementById("ul1");
   oUl.onclick = function(){
        alert(123);
    }
}

 

Here to do with the parent ul event processing, when the li is clicked, due to the bubble theory, the event will bubble to the ul, because there click on ul event, so the event is triggered, of course, click here ul time also triggers, then the problem comes, if I want the event broker effect directly to the event with the effect of how to do the same node, for example, will trigger only click on li, not afraid, we have trick:

Event object provides a property called target, the target node may return to the event, we become an event source, that is to say, target can be expressed as a current event dom operation, but not really operate dom, of course, that there is compatibility the standard browser with ev.target, IE browser with event.srcElement, this time just get the position of the current node does not know what the name of the node, where we use the nodeName to get specifically what label name, this returns an uppercase, lowercase do we need to turn to a comparison (habit):

Copy the code

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);
    }
  }
}

Copy the code

 

Under such a change will only click on the li a trigger event, and each operation is performed only once dom, if the number of li many words, will greatly reduce the operating dom, optimized performance can be imagined!

 

The above example is li said the operation is the same effect, if each li is clicked effect is not the same, then with event delegates still relevant?

<div id="box">
        <input type="button" id="add" value="添加" />
        <input type="button" id="remove" value="删除" />
        <input type="button" id="move" value="移动" />
        <input type="button" id="select" value="选择" />
    </div>
Copy the code
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('添加');
            };
            Remove.onclick = function(){
                alert('删除');
            };
            Move.onclick = function(){
                alert('移动');
            };
            Select.onclick = function(){
                alert('选择');
            }
            
        }
Copy the code

 

I realize the effect of the above is not to say, quite simply, 4 button, click on each do different operations, you need at least four times dom operation, if the event delegate, to optimize it?

Copy the code
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('添加');
                            break;
                        case 'remove' :
                            alert('删除');
                            break;
                        case 'move' :
                            alert ( 'moves');
                            break;
                        Case 'SELECT': 
                            Alert ( 'select'); 
                            BREAK; 
                    } 
                } 
            } 
            
        }
Copy the code

 

With event delegates can only be used once to complete all operations dom effect than the above performance is certainly better than some of 

 

 Now is telling the document load operation under the existing dom node to complete, then if a new node, the new node will be an event you? In other words, a new employee comes, he can receive express it?

Look at the normal method to add a node:

Copy the code
<input type="button" name="" id="btn" value="添加" />
    <ul id="ul1">
        <li>111</li>
        <li>222</li>
        <li>333</li>
        <li>444</li>
    </ul>
Copy the code

 

Now is moved li, li red, out of li, li white, so one effect, then click the button, you can add a child node to ul li in

 

Copy the code
= function the window.onload () { 
            var oBtn = document.getElementById ( "BTN"); 
            var Oul = document.getElementById ( "UL1"); 
            var aLi = oUl.getElementsByTagName ( 'Li'); 
            var. 4 = NUM; 
            
            / / mouse into red, white out 
            for (var I = 0; I <aLi.length; I ++) { 
                aLi [I] .onmouseover = function () { 
                    this.style.background = 'Red'; 
                }; 
                aLi [ I] .onmouseout = function () { 
                    this.style.background = '#fff'; 
                } 
            } 
            // Add a new node 
            oBtn.onclick = function () { 
                NUM ++;
                var oLi = document.createElement ( 'li' ); 
                oLi.innerHTML = 111 * num; 
                oUl.appendChild (oLi); 
            }; 
        }
Copy the code

 

This is a general practice, but you will find that the new li is not an event, indicating time to add child nodes, no events added to it together, it's not the result we want, then how to do it? The general solution would be, coated with a loop for the up function, named mHover, as follows:

Copy the code
window.onload = function(){
            var oBtn = document.getElementById("btn");
            var oUl = document.getElementById("ul1");
            var aLi = oUl.getElementsByTagName('li');
            var num = 4;
            
            function mHover () {
                //鼠标移入变红,移出变白
                for(var i=0; i<aLi.length;i++){
                    aLi[i].onmouseover = function(){
                        this.style.background = 'red';
                    };
                    aLi[i].onmouseout = function(){
                        this.style.background = '#fff';
                    }
                }
            }
            mHover (); 
            Xin tian_jia jie_dian // 
            oBtnonclick = function () { 
                num ++; 
                var oLi = document.createElement ( 'li' ); 
                oLi.innerHTML = 111 * num; 
                oUl.appendChild (oLi); 
                mHover (); 
            }; 
        }
Copy the code

 

Although the function realized, looking quite good, but in fact no doubt added a dom operation, optimized performance is not desirable, then there is event-delegate, can do to optimize it?

Copy the code
window.onload = function(){
            var oBtn = document.getElementById("btn");
            var oUl = document.getElementById("ul1");
            var aLi = oUl.getElementsByTagName('li');
            var num = 4;
            
            //事件委托,添加的子元素也有事件
            oUl.onmouseover = function(ev){
                var ev = ev || window.event;
                var target = ev.target || ev.srcElement;
                if(target.nodeName.toLowerCase() == 'li'){
                    target.style.background = "red";
                }
                
            };
            oUl.onmouseout = function(ev){
                var ev = ev || window.event;
                var target = ev.target || ev.srcElement;
                if(target.nodeName.toLowerCase() == 'li'){
                    target.style.background = "#fff";
                }
                
            };
            
            //添加新节点
            oBtn.onclick = function(){
                num++;
                var oLi = document.createElement('li');
                oLi.innerHTML = 111*num;
                oUl.appendChild(oLi);
            };
        }
Copy the code

 

Look, the above event is commissioned by the way, is the newly added sub-elements with the effect of the event, we can see that, when entrusted with the event, do not need to traverse the children of the element, just give the parent element Add an event like, the other is performed js inside, which can greatly reduce the operating dom, this is the essence of the event delegate.

to sum up:

What kind of events can be entrusted with the event, what kind of events can not use it?

Commissioned for the event with the event: click, mousedown, mouseup, keydown, keyup, keypress.

It is noteworthy that, although there are mouseover and mouseout event bubbling, but when dealing with them need special attention, as it is often calculate their position, not easy to deal with.

There are a lot of inappropriate, for example, mousemove, every time calculate its location, very good to control, in characteristic rather focus, blur and the like, with no bubbling itself, naturally You can not use the event delegation.

 

Guess you like

Origin www.cnblogs.com/lauzhishuai/p/11263210.html