- ?所有的事件存放在一个对象中
- 每个事件的回调函数是一个数组,有多个回调
class EventBus {
allEvent = {}
constructor() {
//
}
on(name, callback) {
if (this.allEvent[name]) {
this.allEvent[name] = [...this.allEvent[name], callback]
return
}
this.allEvent[name] = [callback]
}
off(name, callback) {
if (!this.allEvent[name]) {
return new Error('no event')
}
// once
if (!callback) {
delete this.allEvent[name]
return
}
const target = this.allEvent[name].filter(item => callback !== item)
if (target.length) {
this.allEvent[name] = target
} else {
return new Error('no callback')
}
}
emit(name) {
if (!this.allEvent[name]) {
return new Error('no event')
}
const callbackArr = this.allEvent[name]
const params = [...arguments].slice(1)
callbackArr.forEach(item => {
item(...params)
})
}
once(name, ...args) {
this.emit(name, ...args)
this.off(name)
}
}
const eventBus = new EventBus()
function setName(name) {
console.log('触发 setname', name)
}
function setName1(name) {
console.log('触发 setname1', name)
}
eventBus.on('set-name', setName)
eventBus.on('set-name', setName1)
// eventBus.once('set-name', 'once')
// eventBus.off('set-name', setName1)
eventBus.emit('set-name', 'cat')
setTimeout(() => {
eventBus.emit('set-name', 'dog')
}, 1000);
function setAge(age) {
console.log('设置age', age)
}
// eventBus.on('set-age', setAge)
// eventBus.off('set-age', setAge)
// eventBus.once('set-age', '12')