事件总线 EventBus

TODO: Vue 中的用法

// 方式一:
const eventBus = new Vue();

eventBus.$on('event', (e) => {...});
eventBus.$emit('event', ...params);
eventBus.$off('event');

// 方式二:

实现EventBus

Class EventBus {
  constructor(){
    this.events = {};
  }
  $on(eventName, callback, isOnce) {
    const callbackArr = this.events[eventName];
    if(!callbackArr){
      this.events[eventName] = [];
    }
    this.events[eventName].push({callback, isOnce});
  }
  $emit(eventName, ...args) {
    const callbackArr = this.events[eventName];
    if(callbackArr) {
      this.events[eventName] = callbackArr.filter({callback, isOnce} => {
        callback.apply(this, args);
        return !isOnce
      })
    }
  }
  $off(eventName, callback){
    const callbackArr = this.events[eventName];
    if(!callbackArr){
      return;
    }
    if(callback){
      this.events[eventName] = callbackArr.filter(item => item.callback !== callback)
    }else{
      this.events[eventName] = null;
    }
  }
  $once(eventName, callback) {
    this.on(eventName, callback, true);
  }
}
上次更新:
Contributors: jiangjingmin