Home  >  Article  >  Web Front-end  >  Encapsulates a Javascript event listener that supports anonymous functions_javascript skills

Encapsulates a Javascript event listener that supports anonymous functions_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:46:041279browse

Everyone uses event monitoring in js a lot. It is just to determine whether the browser supports addEventListener and attachEvent. There are many methods of event monitoring found online, but some of them are not perfect. The method below is the same for adding event listeners, except that some operations have been performed on canceling event binding. Now it can support the use of anonymous functions, so there is no need to name the function separately when binding events. .


Main code:

Copy code The code 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 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 el.detachEvent("on" type, handleHash[type][i]);
}
};
};
}
})() ;

Principle analysis:

handleHash functions as a hash table cache event. handleHash['event name'] is an array to add multiple event listening methods. When unbinding which event, traverse the array of handleHash['event name'], and then Remove.

Use:

Copy code The code is as follows:

bind (obj,'click',function(){
alert ('click');
});
unbind(obj,'click');
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