leeword / blog

总结 沉淀 分享
3 stars 0 forks source link

【手写代码】事件发布订阅模式 #4

Open leeword opened 3 years ago

leeword commented 3 years ago
class Event {
  constructor() {
    this.eventList = Object.create(null);
  }

  $on(event, fn) {
    (this.eventList[event] || (this.eventList[event] = [])).push(fn);
  }

  $off(event, fn) {
    let fns = this.eventList[event];
    if (!fns) return false;

    if (!fn) {
      fns.length = 0;
    } else {
      const fnIndex = fns.indexOf(fn);

      if (fnIndex >= 0) {
        fns.splice(fnIndex, 1);
      }
    }
  }

  $once(event, fn) {
    const onceWrapper = (...args) => {
      this.$off(event, onceWrapper);
      fn.apply(this, args);
    }

    this.$on(event, onceWrapper);
  }

  $trigger(event, ...args) {
    const fns = this.eventList[event];
    if (!fns) return false;

    fns.forEach(fn => fn.apply(this, args));
  }
}

export default Event;