Encapsulates a Javascript event listener that supports anonymous functions

  • 2020-03-30 03:10:43
  • OfStack


Main code:



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 [' event name '] is an array to add multiple event listening methods, unbind which event when traversing the handleHash[' event name '] array, and then remove.

Use:


bind(obj,'click',function(){
 alert ('click');
});
unbind(obj,'click');


Related articles: