class EventBus {
// {
// key1:[
// {fn:fn1,isOnce:false},
// {fn:fn2,isOnce:false},
// {fn:fn3,isOnce:true}
// ]
// }
constructor(){
this.events={}
}
on(type,fn,isOnce=false){
const events = this.events;
if(!events[type]){
events[type]=[]
}
events[type].push({fn,isOnce})
} // 绑定
once(type,fn,isOnce=true){
this.on(type,fn,isOnce);
} //绑定一次
off(type,fn){
if(!fn){
this.events[type]=[];
}else{
const fnList = this.events[type];
if(fnList){
this.events[type] = fnList.filter((item)=>item.fn !==fn)
}
}
} //解绑
trigger(type,...args){
const fnList = this.events[type];
if(!fnList) {return} ;
this.events[type] = fnList.filter((item)=>{
const {fn,isOnce} = item;
fn(...args);
if(!isOnce){ return true } //isOnce 为false
return false
})
}//触发事件
}
;
const e = new EventBus();
function fn1(a,b){
console.log('fn1',a,b)
}
function fn2(a,b){
console.log('fn2',a,b)
}
function fn3(a,b){
console.log('fn3',a,b)
}
e.on('key1',fn1);
e.on('key1',fn2);
e.once('key1',fn3);
e.trigger('key1',1,2);
e.off('key1',fn1);
e.trigger('key1',3,4);
console