Home > Web Front-end > JS Tutorial > body text

Event delegation in js

小云云
Release: 2018-03-14 16:59:07
Original
1642 people have browsed it

This article mainly shares with you the detailed explanation of event delegation examples in js. We mainly share with you two contents: 1. The principle and advantages and disadvantages of event delegation. 2. Handwritten native js to implement event delegation and its requirements. Browser compatible.

Q: The principles and advantages and disadvantages of event delegation (Delegated Events)

A: Delegated (agent) events are those bound Events assigned to parent elements, but will only be moved when certain matching conditions are met. This is achieved by the event bubbling mechanism.

The advantages are:

(1) It can save a lot of memory usage and reduce events Registration, for example, it would be great to proxy all td click events on the table

(2) It can be realized that when a new sub-object is added, there is no need to bind the event to it again, for the dynamic content part Particularly suitable

The disadvantage is:

The commonly used applications of event proxies should be limited to the above requirements. If all events are used as proxies, it is possible Event misjudgment will occur, that is, events that should not be triggered are tied to events.

Example:

##
var toolbar = document.querySelector(".toolbar");
toolbar.addEventListener("click", function(e) {
  var button = e.target;
  if(!button.classList.contains("active"))
    button.classList.add("active");
  else
    button.classList.remove("active");
});
Copy after login



Clicking the button element will bubble up to the UL.toolbar element, and e.target is used to locate the currently clicked button.

Q: Hand-written native js implements event proxy and requires browser compatibility

A: In fact, it is to assess the understanding of the event object e , and the corresponding attribute name under IE.

View Demo

function delegateEvent(interfaceEle, selector, type, fn) {// ============ 简单的事件委托
    if(interfaceEle.addEventListener){
    interfaceEle.addEventListener(type, eventfn);
    }else{
    interfaceEle.attachEvent("on"+type, eventfn);
    }
    function eventfn(e){
    var e = e || window.event;    
    var target = e.target || e.srcElement;
 
  
 //如果目标元素与选择器匹配则执行函数
    if (matchSelector(target, selector)) {
            if(fn) {
 //将fn内部的this指向target(在此之前this都是指向的绑定事件的元素即interfaceEle)
                fn.call(target, e); 
            }
        }
    }
}
/**
 * only support #id, tagName, .className
 * and it's simple single, no combination
 */
//比较函数:判断事件的作用目标是否与选择器匹配;匹配则返回true
function matchSelector(ele, selector) {
    //
 如果选择器为ID
    if (selector.charAt(0) === "#") {
            
        return ele.id === selector.slice(1);
   
    }
 
     //charAt(0),返回索引为0的字符
 
   //slice(a,b),从已有的数组或字符串返回从索引从a处开始,截取到索引b之前的子数组或子字符串;
    //如果选择器为Class
    if (selector.charAt(0) === ".") {
        return (" " + ele.className + " ").indexOf(" " + selector.slice(1) + " ") != -1;
    }
    //
 如果选择器为tagName
    return ele.tagName.toLowerCase() === selector.toLowerCase();
}
//toLowerCase()将字符串转换成小写
//调用
var op = document.getElementById("op");
delegateEvent(op,"a","click",function(){
    alert("1");
})
Copy after login
Related recommendations:


Detailed explanation of JS event delegation instance

The above is the detailed content of Event delegation in js. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template