You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Event.prototype.emit=function(type){// 做个容错处理,判断缓存中有无传入的事件类型if(!this.cache[type]){throw'no this type of event';}// 取得参数(可有可无)varargs=Array.prototype.slice.call(arguments,1);// 获取对应事件类型绑定回调的个数varlen=this.cache[type].length;// 传入参数,执行回调for(vari=0;i<len;i++){this.cache[type][i].apply(this,args);}}
我们再添加一个退订的功能:
Event.prototype.remove=function(type,handler){// 例行检查if(!this.cache[type]){throw'no this type of event';}// 筛选出除了handler以外的其他回调组成新的list[type]this.cache[type]=this.cache[type].filter(function(ele){returnele!=handler;})}
至此,我们完成了一个简单的Event模块,接着我们来测试一下:
varoE=newEvent();// 订阅一个获取时间的东东oE.listen('getTime',function(time){console.log('Now is '+time);})oE.listen('getTime',function(time){console.log(time+' is good');})// 发布当前时间oE.emit('getTime',newDate());
没问题~
The text was updated successfully, but these errors were encountered:
于是我们事不宜迟,来实现一个简单的Event模块,其就有发布消息、订阅消息、退订消息等功能。
接着我们来实现订阅:
再接着,我们来实现发布:
我们再添加一个退订的功能:
至此,我们完成了一个简单的Event模块,接着我们来测试一下:
没问题~
The text was updated successfully, but these errors were encountered: