To be compatible with various browsers, I have nothing to do with reviewing the js native event features and encapsulating them. Do not explain. Check the Code:
The Code is as follows:
; (Function (){
// Encapsulate the database to prevent object contamination
Window ['cm '] = {};
/**
* Registering an event for an object
*/
Var addListener = function (element, type, fn ){
If (typeof element = 'undefined') return false;
If (element. addEventListener ){
Element. addEventListener (type, fn, false );
} Else if (element. attachEvent ){
// Buffer the event to this tag. The problem that this points to window (now this points to element in fn) and the problem of removing anonymous events has been solved.
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;
/**
* Remove registered events from an 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 = '_' + 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;
}
};
})();