Home >Web Front-end >JS Tutorial >Common methods about js registration events_javascript skills

Common methods about js registration events_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:38:331258browse

No explanation, look at the code:

Copy code The code is as follows:

;(function(){
//Library encapsulation to prevent object pollution
window['cm']={};
/**
*Register events for objects
*/
var addListener=function(element,type,fn){
if(typeof element == 'undefined') return false;
if(element.addEventListener){
element.addEventListener(type,fn, false);
}else if(element.attachEvent){
var _EventRef='_' type 'EventRef';
                                                                                                              _EventRefs=element[_EventRef];
var index;
for(index in _EventRefs){
if(_EventRefs[index]['realFn']==fn){
return;
                                                                                                                                                                                                                                                var nestFn=function(){
                  fn.apply(element,arguments); 🎜>           element.attachEvent('on' type, nestFn); ]['addListener']=addListener;
/**
*Remove registered events on the object
*/
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='_' 'EventRef' ;
                                                                                                                                                                                                            🎜> var index;
var nestFn;
for(index in _EventRefs){
if(_EventRefs[index]['realFn']==fn){
nestFn=_EventRefs[index]['nestFn'];
if(index ==_EventRefs.length-1){
                                                                                                                                                           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;
        }
    };
})();

 

Statement:
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