首页 > 技术文章 > js事件绑定--支持匿名函数解除绑定

walle2 2015-10-22 11:38 原文

废话不多说,直接上代码

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元素。解除绑定时判定是否已经绑定过某事件,如果是解除所有的事件处理函数

 

参考: Js事件监听封装(支持匿名函数)

推荐阅读