您的位置:首页 > 其它

简单的事件处理类Event

2017-07-31 15:19 204 查看
class Event{
constructor(){
this.handlers=[]
}
on(type,fn){  //订阅事件
if(!this.handlers[type]){
this.handlers[type] = [];
}
this.handlers[type].push({handle:fn,one:false});
}
one(type,option={},fn){ //订阅只执行一次的事件
if(!this.handlers[type]){
this.handlers[type] = [];
}
this.handlers[type].push({handle:fn,one:true});
}
emit(type,option,fn){ //发布某类事件或者某个事件,fn存在时候只执行订阅过的fn事件
var handlers = this.handlers[type]
for (var i=0, len=handlers.length; i < len; i++){
if(fn){
if(handlers[i].handle === fn){
handlers[i].handle(option)
if(handlers[i].one){
handlers.splice(i, 1);
}
break;
}
}else {
handlers[i].handle(option)
if(handlers[i].one){
handlers.splice(i, 1);
}
}

}
}
remove(type,fn){  //移除某类事件或者某个事件,fn存在即移除该事件
var handlers = this.handlers[type]
if(fn){
for (var i=0, len=handlers.length; i < len; i++){
if(handlers[i] === fn){
handlers.splice(i, 1);
break;
}
}
}else {
delete this.handlers[type];
}
}
}
export default new Event();


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: