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