var handleHash = {};
var bind = (function () {
if (window.addEventListener){
return function (e1, type, fn, capture) {
e1.addEventListener(type,function () {
fn();
handleHash[type] = handleHash[type]||[];
handleHash[type].push(arguments.callee);
},capture);
}
}else if (window.attachEvent){
return function (e1, type, fn, capture) {
e1.attachEvent("on"+type,function () {
fn();
handleHash[type] = handleHash[type]||[];
handleHash[type].push(arguments.callee);
})
}
}
})();
var unbind = (function () {
if (window.addEventListener){
return function (e1, type) {
if(handleHash[type]){
var i=0,len=handleHash[type].length;
for (i;i<len;i++){
e1.removeEventListener(type,handleHash[type][i]);
}
}
};
}else if (window.attachEvent){
return function (e1, type) {
if(handleHash[type]){
var i=0,len=handleHash[type].length;
for (i;i<len;i++){
e1.detachEvent(type,handleHash[type][i]);
}
}
};
}
})();
解析:
handleHash用作哈希表来存储事件的function,handleHash【type】来存储多个事件监听的方法,当需要移除哪个事件,遍历handleHash【type】的数组,删除事件。