跳至主要內容

6. 事件总线

鸭梨小于 1 分钟

6. 事件总线

使用发布订阅模式实现事件总线:

class EventEmitter {
  constructor() {
    this.cache = {}
  }

  emit(name, once = false, ...args) {
    if (this.cache[name]) {
      // 创建副本,如果回调函数内继续注册相同事件,会造成死循环
      const tasks = this.cache[name].slice()
      for (const fn of tasks)
        fn(...args)

      if (once)
        delete this.cache[name]
    }
  }

  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)
    }
  }

  on(name, fn) {
    if (this.cache[name])
      this.cache[name].push(fn)
    else
      this.cache[name] = [fn]
  }
}

事件总线

实现事件总线第三方库有 emitteryopen in new windowevent-emitteropen in new windowmittopen in new window