eventBus的实现

2021-04-04  本文已影响0人  小杰66
//即发布订阅模式的简单实现
class EventEmeitter {
  constructor() {
    this.events = {};
  }

  emit(type, ...args) {
    (this.events[type] || []).forEach((fun) => fun.apply(this, args));
  }

  addListener(type, fun) {
    if (!this.events[type]) this.events[type] = [];
    this.events[type].push(fun);
  }

  removeListener(type, fun) {
    let funs = this.events[type] || [];
    let index = funs.indexOf(fun);
    if (index > -1) {
      this.events[type].splice(index, 1);
    }
  }
}
上一篇 下一篇

猜你喜欢

热点阅读