js-简单的发布订阅类

61 阅读1分钟

核心思想

  • 用个全局变量存储订阅函数
  • emit 触发时遍历对应数组的每个变量并执行
  • off 时将对应函数从数组中删除

//这里省略的一些边界处理,只是为了极简的表达核心实现方法

class Observe {
  cb = {}

  on(eventName, fn) {
    this.cb[eventName] = this.cb[eventName] || []
    this.cb[eventName].push(fn)
  }

  emit(eventName, data) {
    let arr = this.cb[eventName]
    if (arr) {
      arr.forEach((fn) => {
        fn(data)
      })
    }
  }

  off(eventName, fn) {
    let arr = this.cb[eventName]
    if (arr) {
      let newArr = fn ? arr.filter((e) => {
        return e !== fn
      }) : []
      this.cb[eventName] = newArr
    }
  }
}