使用javascript的“委托”实现attachEvent
使用javascript的“委托”實現attachEvent
上次介紹過使用js來實現委托的特性,今天說一下使用委托實現一些有用的功能。
例如實現類似ie dom對象的其中一個方法:attachEvent
attachEvent這個方法是用來綁定對象事件,在大量使用互交時的中經常會用到這個方法,不過在ie和firefox是使用不同的方法來實現,我們可以使用委托來重寫這個方法:
/**
*function:用委托的思想實現對象的事件綁定
*author:天邊一只雁
*blog:http://harrychen66.cnblogs.com/
*/
//實現委托的類
functiondelegate(func){
this.arr=newArray();//回調函數數組
this.add=function(func){
this.arr[this.arr.length]=func;
};
this.run=function(){
for(vari=0;i<this.arr.length;i++){
varfunc=this.arr[i];
if(typeoffunc=="function"){
func();//遍歷所有方法以及調用
}
}
}
this.add(func);
}
//新建一個實現attachevent的函數
functionfAttachEvent(obj,sEvent,func){
if(!obj.dEv)obj.dEv=newdelegate();
obj.dEv.add(func);
eval("obj."+sEvent+"=function(){this.dEv.run()}");
}
//建立一個button
varbtn=document.createElement("BUTTON");
btn.value="action";
//綁定函數1
varrenderButton=function(){
document.body.appendChild(btn);
};
//綁定函數2
varaction1=function(){
alert("action1");
};
//綁定函數3
varaction2=function(){
alert("action2");
};
//綁定函數1到window對象的onload事件
fAttachEvent(window,"onload",renderButton);
//綁定函數2到btn對象的onclick事件
fAttachEvent(btn,"onclick",action1);
//綁定函數3到btn對象的onclick事件
fAttachEvent(btn,"onclick",action2);
總結
以上是生活随笔為你收集整理的使用javascript的“委托”实现attachEvent的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 「已解答」2斤鲈鱼一般蒸多长时间
- 下一篇: 450m无线路由器怎么安装450m路由器