class EventBus {
constructor() {
this.events = {}
}
addEve (eventName,eventFn) {
//console.log(this.events)
this.events[eventName] = {
eventFn,
once:false
}
}
emit (eventName,msg) {
let key = Object.keys(this.events)
if(key.includes(eventName)){ //如果找到了这个事件就执行
if(this.events[eventName].once) {
delete this.events[eventName]
}else{
this.events[eventName].eventFn(msg)
}
}
}
removeEve (eventName,eventFn) {
let key = Object.keys(this.events)
if(key.includes(eventName)){
delete this.events[eventName]
}
console.log(this.events)
}
once(eventName,eventFn){
this.events[eventName] = {
eventFn,
once:true
}
console.log(this.events)
}
}
let event = new EventBus()
event.addEve('class1',function class1(msg){
console.log("class1---"+ msg)
})
event.addEve('class2',function class2(msg){
console.log("class2---"+ msg)
})
event.addEve('class3',function class3(msg){
console.log("class3---"+ msg)
})
event.emit('class1','第一个事件')
event.emit('class2','第2个事件')
event.emit('class3','第3个事件')
// event.once('class3','class3')
//event.removeEve('class3')
event.once('class3',function class3(msg){
console.log("class3---"+ msg)
})
event.emit('class3','第3个事件')
//event.emit('class3','第3个事件')
event.removeEve('class2','class2')
event.emit('class2','第2个事件')
//输出
class1---第一个事件
class2---第2个事件
class3---第3个事件
{
class1: { eventFn: [Function: class1], once: false },
class2: { eventFn: [Function: class2], once: false },
class3: { eventFn: [Function: class3], once: true }
}
{ class1: { eventFn: [Function: class1], once: false } }
[Done] exited with code=0 in 0.122 seconds