JS event delegate (the event broker, dom2 level events)

I. Introduction

  To be honest, I really ask me what event delegation, I am sure gg, better search a bit, but it was before I practiced application of DOM2-level events.

Second, what is the event delegate?

  Event delegation is when the event occurs, the delegate to do to parent element (or parent of the parent element) to deal with. That is: the use of the principle of bubbling, the event is added to the parent, is determined by the event source subset, performing a corresponding operation. Use event delegation technique will prevent you from adding event listeners for each specific node.

Third, the role of event delegates

  1. Reduce the event registration, save memory

    -table td can represent all the click event

    -ul can represent all the click event li

  2. able to after the new DOM element is automatically added events (event entrusted to the parent, as long as the child can proxy)

    - The new li not bind events

    - When deleting li, does not require unbundling

Case presentation:

Scene 1: when a plurality of tags to add mouseover color li

Results as shown:

ul{
  width: 200px;
  line-height: 30px;
}
li.checked{
  background-color: aqua;
}
< H2 > Where to open the room? </ H2 > 
< ul > 
  < li > your home </ li > 
  < li > my </ li > 
  < li > Home </ li > 
</ ul >

You do not need to traverse the event delegates add event

window.onload = function(){
    let oLi = document.getElementsByTagName('li');
    for(let i=0,len=oLi.length;i<len;i++){    // 遍历所有li
        oLi[i].onmouseover = function () {
          this.classList.add('checked')
        }
        oLi[i].onmouseout = function () {
            this.classList.remove('checked')
        }
    }
}

Use event delegation

= the window.onload function () { 
    the let Oul = document.getElementsByTagName ( 'UL') [0 ];
     function beenChecked (E) {                 // E event is an event 
        e.target.classList.add ( 'the checked')     // E .target is the event source 
    }
     function notChecked (E) { 
        e.target.classList.remove ( 'the checked' ) 
    } 
    oUl.addEventListener ( 'mouseOver', beenChecked)   // third parameter default false, event bubbling 
    oUl.addEventListener ( 'mouseOut' , notChecked) 
}    

Fourth, the shortcomings

  1. delegate event-based bubble, for the onfocus and onblur events are not supported.

  2. excessive levels, bubbling process, there may be a layer prevents out (the nearest commission recommended)

  As long as the event does not support the bubble or on the way there event.stopPropagation (), etc., then the commission will fail, so do not apply commissioned directly on the document.

Guess you like

Origin www.cnblogs.com/danew/p/11551284.html