js事件綁定--支持匿名函數解除綁定

廢話很少說,直接上代碼函數

var handlers = {},
    bind = (function (){
        if(window.addEventListener){
            return function (el, type, callback, capture){
                el.addEventListener(type, function (){
                    callback();
                    handlers[type] = handlers[type] || [];
                    handlers[type].push(arguments.callee);
                }, !!capture);
            }
        }else if(window.attachEvent){
            return function (el, type, callback){
                el.attachEvent('on'+type, function (){
                    callback.call(el);
                    handlers[type] = handlers[type] || [];
                    handlers[type].push(arguments.callee);
                });
            }
        }else{
            return function (el, type, callback){
                el.on+'type' = callback;
            }
        }
    }(window)),
    unbind = (function (){
        if(window.addEventListener){
            return function (el, type){
                if(handlers[type]){
                    var i=0, len = handlers[type].length;
                    for (; i<len; i++) {
                        el.removeEventListener(type, handlers[type][i]);
                    };
                }
            }
        }else if(window.attachEvent){
            return function (el, type){
                if(handlers[type]){
                    var i=0, len = handlers[type].length;
                    for(; i<len; i++){
                        el.detachEvent('on'+type, handlers[type][i]);
                    }
                }
            }
        }else{
            return function (el, type){
                el.on+'type' = null;
            }
        }
    }(window));

綁定時用一個空對象來保存事件的回調,在IE下回調函數用 call 保證this指向當前綁定事件的DOM元素。解除綁定時斷定是否已經綁定過某事件,若是是解除全部的事件處理函數this

 

參考: Js事件監聽封裝(支持匿名函數)spa

相關文章
相關標籤/搜索