class EventBus {
constructor() {
this.cache = {}
}
subscribe(eventName, callback) {
if (!this.cache[eventName]) {
this.cache[eventName] = []
}
this.cache[eventName].push(callback)
}
unSubscribe(eventName, callback) {
const tasks = this.cache[eventName]
if (tasks) {
this.cache[eventName] = tasks.filter(fn => fn !== callback)
}
}
publish(eventName, once = false, ...args) {
if (this.cache[eventName]) {
const tasks = this.cache[eventName].slice()
for (let fn of tasks) {
fn(...args)
}
if (once) {
delete this.cache[eventName]
}
}
}
}
let eventBus = new EventBus()
let fn1 = function(name, age) {
console.log(`${name} ${age}`)
}
let fn2 = function(name, age) {
console.log(`hello, ${name} ${age}`)
}
eventBus.subscribe('aaa', fn1)
eventBus.subscribe('aaa', fn2)
eventBus.publish('aaa', false, '布兰', 12)