wang1dot0 / personal-note

记录工作中遇到的个人觉得比较有意思的小问题
https://github.com/wang1dot0/personal-note
0 stars 0 forks source link

[js] 观察者模式 / 发布订阅模式 #33

Open wang1dot0 opened 4 years ago

wang1dot0 commented 4 years ago

观察者模式

发布订阅模式

class SubPub {
  constructor() {
    this.handlers = {};
  }
  on(event, handler) {
    if (!this.handlers.hasOwnproperty(event)) {
      this.handlers[event] = [];
    }

    if (typeof handler !== 'function') {
      throw new Error('handler must be a function.');
    }

    this.handlers[event].push(handler);
    return this;
  }
  emit(event, ...args) {
    if(!this.handlers.hasOwnproperty(event)) {
      throw new Error('No event: ', event);
    }
    this.handlers[event].forEach(func => {
      func.apply(null, args);
    });
  }
  off(event, handler) {
    if(!this.handlers.hasOwnproperty(event)) {
      throw new Error('No event: ', event);
    }
    if (typeof handler !== 'function') {
      throw new Error('handler must be a function.');
    }
    this.handlers[event].forEach((func, idx) => {
      if (func === handler) {
        this.handlers[event].splice(idx, 1);
        return false;
      }
    });
  }
}