事件委託優缺點和實現

看風景就發表於2017-03-06
function fDelegate(parentSelector,targetSelector,event,callback){
    var parent = document.querySelector(parentSelector);
    parent.addEventListener(event,fEventHandler,false);

    function fEventHandler(e){
        var target = e.target,
            //currentTarget = e.currentTarget;//parent代替
        while(target != parent){
            if(target.matches(targetSelector)){
                callback.apply(target,Array.prototype.slice.call(arguments));
                break;
            }
            target = target.parentNode;
        }
    }
}

if (!Element.prototype.matches) {
  Element.prototype.matches =
    Element.prototype.matchesSelector ||
    Element.prototype.mozMatchesSelector ||
    Element.prototype.msMatchesSelector ||
    Element.prototype.oMatchesSelector ||
    Element.prototype.webkitMatchesSelector ||
    function(s) {
      var matches = (this.document || this.ownerDocument).querySelectorAll(s),
      i = matches.length;
      while (--i >= 0 && matches.item(i) !== this) {}
      return i > -1;
    };
}

呼叫:

fDelegate('#list', 'li', 'click', function () { console.log(this); });

事件委託優點:

1.減少記憶體消耗,不必為大量元素繫結事件
2.為動態新增的元素繫結事件

事件委託的缺點:

1.部分事件如 focus、blur 等無冒泡機制,所以無法委託。
2.事件委託有對子元素的查詢過程,委託層級過深,可能會有效能問題
3.頻繁觸發的事件如 mousemove、mouseout、mouseover等,不適合事件委託

相關文章