class MyEventBus{
constructor() {
this.events = {};
}
on(eventName, callBack){
if(!this.events[eventName]){
this.events[eventName] = [];
}
this.events[eventName].push(callBack);
}
emit(eventName, ...args){
if(!this.events[eventName]){
throw new Error('error');
}
const eventList = [...this.events[eventName]];
for(let fn of eventList){
fn.apply(null, args);
}
}
off(eventName = '', fn = null){
if(!eventName){
this.events = [];
}else if(fn === null){
this.events[eventName] = [];
}else{
const index = this.events[eventName].indexOf(fn);
index === -1 ? '' : this.events[eventName].splice(index, 1);
}
}
}
const event = new MyEventBus();
const foo = (...args) => console.log(args);
event.on('test', foo);
event.emit('test', '1')
event.off('test', foo);
event.emit('test', '2')
11-15
86
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
06-22
07-18
07-18
07-18
07-18
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交