使用javascript的“委托”实现attachEvent

使用javascript的“委托”实现attachEvent

上次介绍过使用js来实现委托的特性,今天说一下使用委托实现一些有用的功能。
例如实现类似ie dom对象的其中一个方法:attachEvent
attachEvent这个方法是用来绑定对象事件,在大量使用互交时的中经常会用到这个方法,不过在ie和firefox是使用不同的方法来实现,我们可以使用委托来重写这个方法:
/**
 * function: 用委托的思想实现对象的事件绑定
 * author:   天边一只雁
 * blog:     http://harrychen66.cnblogs.com/
 
*/
// 实现委托的类
function delegate(func){
    
this.arr = new Array(); // 回调函数数组
    this.add = function(func){
        
this.arr[this.arr.length] = func;
    };
    
this.run = function(){
        
for(var i=0;i<this.arr.length;i++){
            
var func = this.arr[i];
            
if(typeof func == "function"){
                func(); 
// 遍历所有方法以及调用
            }
        }
    }
    
this.add(func);
}
// 新建一个实现attach event的函数
function fAttachEvent(obj,sEvent,func){
    
if(!obj.dEv) obj.dEv = new delegate();
    obj.dEv.add(func);
    eval(
"obj." + sEvent + " = function(){this.dEv.run()}");
}
// 建立一个button
var btn = document.createElement("BUTTON");
btn.value 
= "action";
// 绑定函数1
var renderButton = function(){
    document.body.appendChild(btn);
};
// 绑定函数2
var action1 = function(){
    alert(
"action1");
};
// 绑定函数3
var action2 = function(){
    alert(
"action2");
};
// 绑定函数1到window对象的onload事件
fAttachEvent(window, "onload", renderButton);
// 绑定函数2到btn对象的onclick事件
fAttachEvent(btn, "onclick", action1);
// 绑定函数3到btn对象的onclick事件
fAttachEvent(btn, "onclick", action2);
原文地址:https://www.cnblogs.com/niuniu502/p/734138.html