简易版 es6 eventbus

$on 绑定callback, 再由$emit 触发callback

class EventBus {
  constructor() {
    this.events = {}
  }

  $on(event = '', callback) {
    if (typeof callback !== "function") {
      throw 'callback is not function'
      return
    }
    if (!event) {
      throw 'event is not null'
      return
    }
    if (!this.events[event]) {
      this.events[event] = []
    }
    this.events[event].push(callback)
  }

  $emit(event = '', data) {
    if (!event) {
      throw 'event is not null'
      return
    }
    if (!this.events[event]) {
      return
    }
    this.events[event].map(fn => {
      fn(data)
    })
  }

  $off(event = '') {
    if (!event) {
      return
    }
    if (this.events[event]) {
      delete this.events[event]
    }
  }
}

export default new EventBus()

你可能感兴趣的:(简易版 es6 eventbus)