本质就是一个订阅发布模式的实现。
- 维护一个cache数组,即订阅者数组
- 实现on函数,即增加订阅者
- 实现off函数,即取消订阅
- 实现emit函数,即发布消息,通知订阅中心有更新
class EventBus {
constructor() {
this.cache = {};
}
on(name, fn) {
if (this.cache[name]) {
this.cache[name].push(fn);
} else {
this.cache[name] = [fn];
}
}
off(name, fn) {
const tasks = this.cache[name];
if (tasks) {
const index = tasks.findIndex((f) =>
f === fn || f.callback === fn
)
if (index >= 0) {
tasks.splice(index, 1);
}
}
}
emit(name) {
if (this.cache[name]) {
// 创建副本,如果回调函数内继续注册相同事件,会造成死循环
const tasks = this.cache[name].slice()
for (let fn of tasks) {
fn();
}
}
}
emit(name, once = false) {
if (this.cache[name]) {
// 创建副本,如果回调函数内继续注册相同事件,会造成死循环
const tasks = this.cache[name].slice()
for (let fn of tasks) {
fn();
}
if (once) {
delete this.cache[name]
}
}
}
}
const eventBus = new EventBus()
const task1 = () => { console.log('task1'); }
const task2 = () => { console.log('task2'); }
eventBus.on('task', task1)
eventBus.on('task', task2)
setTimeout(() => {
eventBus.emit('task')
}, 1000)
更多详情可以看我博客的另一篇笔记:《设计模式之观察者模式——Js实现》