佳佳佳佳佳佳酱 佳佳佳佳佳佳酱
关注数: 10 粉丝数: 32 发帖数: 355 关注贴吧数: 38
自定义简单事件 先贴函数 function SimpleEvent(){ this.eventid=1; this.eventlist={}; this.eventargrule={}; this.debug=false; this.addEvent=function(ename,fun){ if(typeof ename!="string"){ if(this.debug===true)console.log("事件名不是字符串:",ename); return; } if(!this.eventlist[ename]||typeof this.eventlist[ename].join !="function"){ this.eventlist[ename]=[]; } return [ename,this.eventlist[ename][this.eventlist[ename].push(fun)-1].id=this.eventid++,fun]; }; this.removeEvent=function(eobj){ if(!eobj||typeof eobj!="object"||!eobj.join)return; if(this.eventlist[eobj[0]]&&this.eventlist[eobj[0]].indexOf){ var ind=this.eventlist[eobj[0]].indexOf(eobj[2]); if(ind>=0){ this.eventlist.splice(ind,1); } }else if(this.debug===true){ console.log("移除未定义的事件:",eobj[0]); } }; this.setargrule=function(ename,rulefun){ if(typeof ename!="string"){ if(this.debug===true)console.log("事件名不是字符串:",ename); return; } if(typeof rulefun=="function"){ this.eventargrule[ename]=rulefun; }else if(his.debug===true){ console.log("参数规则不是函数"); } }; this.fireEvent=function(ename){ if(typeof ename!="string"){ if(this.debug===true)console.log("事件名不是字符串:",ename); return; } if((typeof this.eventlist[ename])=="object"){ var th=this; this.eventlist[ename].forEach(function(value){ if(this.debug===true){ console.log("事件触发事件列表:",ename); } if (typeof value == "function") { setTimeout(function(){ if (th.eventargrule[ename]) { value(th.eventargrule[ename]()); return; } value(); },0); }else if(typeof value== "string"){ setTimeout(function(){ try{ eval(value); }catch(e){ if(th.debug===true){ console.log("无法执行事件:",e); } } },0); } }); }else if(this.debug===true){ console.log("未定义的事件:",ename); } }; } 用法 var e=new SimpleEvent(); 监听事件 e.addEvent("miao",function(){ //do... }); 发射事件 e.fireEvent("miao"); 删除事件 var 事件1=e.addEvent("miao",function(){ //do... }); e.removeEvent(事件1);
1 下一页