发布订阅
const eventBus = {
map: {},
on: (name, fn) => {
eventBus.map[name] = eventBus.map[name] || []
eventBus.map[name].push(fn)
},
emit: (name, data) => {
if (!eventBus.map[name]) { return }
eventBus.map[name].map(fn => fn.call(undefined, data))
return undefined
},
off: (name, fn) => {
if (!eventBus.map[name]){ return }
const index = eventBus.map[name].indexOf(fn)
if (index < 0) { return }
eventBus.map[name].splice(index, 1)
}
}
// 使用
eventBus.on('click', console.log)
eventBus.on('click', console.error)
setTimeout(() => {
eventBus.emit('click', 'hello')
}, 1000)
也可以用 class 实现。
class EventHub {
map = {}
on(name, fn) {
this.map[name] = this.map[name] || []
this.map[name].push(fn)
}
emit(name, data) {
const fnList = this.map[name] || []
fnList.forEach(fn => fn.call(undefined, data))
}
off(name, fn) {
const fnList = this.map[name] || []
const index = fnList.indexOf(fn)
if(index < 0) return
fnList.splice(index, 1)
}
}
// 使用
const e = new EventHub()
e.on('click', (name)=>{
console.log('hi '+ name)
})
e.on('click', (name)=>{
console.log('hello '+ name)
})
setTimeout(()=>{
e.emit('click', 'Bumble')
},3000)