People use more about event monitoring in js, but it is nothing more than judging whether the browser supports addEventListener and attachEvent. There are many ways to search for event monitoring online, but some are not very perfect. The following method is the same for adding event listening, except that some surgery was performed on canceling event binding, and the use of anonymous functions can now be supported, so when binding events, no longer need to name the function separately.
Main code:
The code copy is as follows:
/*Binding events and unbinding*/
var handleHash = {};
var bind = (function() {
if (window.addEventListener) {
return function(el, type, fn, capture) {
el.addEventListener(type, function(){
fn();
handleHash[type] = handleHash[type] || [];
handleHash[type].push(arguments.callee);
}, capture);
};
} else if (window.attachEvent) {
return function(el, type, fn, capture) {
el.attachEvent("on" + type, function(){
fn();
handleHash[type] = handleHash[type] || [];
handleHash[type].push(arguments.callee);
});
};
}
})();
var unbind = (function(){
if (window.addEventListener) {
return function(el, type ) {
if(handleHash[type]){
var i = 0, len = handleHash[type].length;
for (i; i<len ; i += 1){
el.removeEventListener(type, handleHash[type][i]);
}
};
};
} else if (window.attachEvent) {
return function(el, type) {
if(handleHash[type]){
var i = 0, len = handleHash[type].length;
for (i; i<len ; i += 1){
el.detachEvent("on" + type, handleHash[type][i]);
}
};
};
}
})();
Principle analysis:
handleHash does the hash table to cache the function of events. handleHash['event name'] is an array to add multiple event listening methods. When unbind which event is unbind, iterate through the array of handleHash['event name'] and then remove it.
use:
The code copy is as follows:
bind(obj,'click',function(){
alert ('click');
});
unbind(obj,'click');