关于js注册事件的常用方法

不解释,看代码:

代码如下:

;(function(){
    //进行库封装,防止对象污染
    window['cm']={};
/**
    *给对象注册事件
    */
    var addListener=function(element,type,fn){
        if(typeof element == 'undefined') return false;
        if(element.addEventListener){
            element.addEventListener(type,fn,false);
        }else if(element.attachEvent){
            //将事件缓冲到该标签上,已解决this指向window(现fn内this指向element)和移除匿名事件问题
            var _EventRef='_'+type+'EventRef';
            if(!element[_EventRef]){
                element[_EventRef]=[];
            }
            var _EventRefs=element[_EventRef];
            var index;
            for(index in _EventRefs){
                if(_EventRefs[index]['realFn']==fn){
                    return;
                }
            }
            var nestFn=function(){
                fn.apply(element,arguments);
            };
            element[_EventRef].push({'realFn':fn,'nestFn':nestFn});
            element.attachEvent('on'+type,nestFn);
        }else{
            element['on'+type]=fn;
        }
    };
    window['cm']['addListener']=addListener;
    /**
    *移除对象上已注册事件
    */
    var removeListener=function(element,type,fn){
        if(typeof element == 'undefined') return false;
        if(element.removeEventListener){
            element.removeEventListener(type,fn,false);
        }else if(element.detachEvent){
            var _EventRef='_'+type+'EventRef';
            if(!element[_EventRef]){
                element[_EventRef]=[];
            }
            var _EventRefs=element[_EventRef]
            var index;
            var nestFn;
            for(index in _EventRefs){
                if(_EventRefs[index]['realFn']==fn){
                    nestFn=_EventRefs[index]['nestFn'];
                    if(index==_EventRefs.length-1){
                        element[_EventRef]=_EventRefs.slice(0,index);
                    }else{
                        element[_EventRef]=_EventRefs.slice(0,index).concat(_EventRefs.slice(index+1,_EventRefs.length-1));
                    }
                    break;
                }
            }
            if(nestFn){
                element.detachEvent('on'+type,nestFn);
            }
        }else{
            element['on'+type]=null;
        }
    };
})();

 

相关推荐