一个简单的EventEmitter

用JS写了一个简单的EventEmitter:

class EventEmitter {
  /**
   * 事件名/回调列表 字典
   * @type {Map<string, Array<function>>}
   * @private
   */
  _callbackListMap = new Map()

  /**
   * 监听事件
   * @param eventName: string
   * @param cb: function
   */
  on(eventName, cb) {
    let cbList = this._callbackListMap.get(eventName)
    if (cbList == null) {
      this._callbackListMap.set(eventName, [])
      cbList = this._callbackListMap.get(eventName)
    }
    if (Array.isArray(cbList)) {
      cbList.push(cb)
    }
  }

  /**
   * 取消监听事件
   * @param eventName: string
   * @param cb: function | null
   */
  off(eventName, cb = null) {
    // 取消监听事件上的所有回调
    if (cb == null) {
      this._callbackListMap.delete(eventName)
    // 取消监听事件上的单个回调
    } else {
      let cbList = this._callbackListMap.get(eventName)
      if (Array.isArray(cbList)) {
        let i = cbList.findIndex(fn => fn === cb)
        if (i > -1) {
          cbList.splice(i, 1)
        }
      }
    }
  }

  /**
   * 触发某个事件
   * @param eventName: string
   * @param rest: Array<any>
   * @protected
   */
  emit(eventName, ...rest) {
    let callbackList = this._callbackListMap.get(eventName)
    if (Array.isArray(callbackList)) {
      callbackList.forEach(fn => fn(...rest))
    }
  }
}

猜你喜欢

转载自www.cnblogs.com/forzhaokang/p/10333192.html