发布订阅模式

285 阅读1分钟

在软件架构中,发布-订阅是一种消息范式,消息的发送者(称为发布者)不会将消息直接发送给特定的接收者(称为订阅者)。而是将发布的消息分为不同的类别,无需了解哪些订阅者(如果有的话)可能存在。同样的,订阅者可以表达对一个或多个类别的兴趣,只接收感兴趣的消息,无需了解哪些发布者(如果有的话)存在。

class EventEmitter {
  constructor() {
    this.eventMap = {};
  }
  on(type, handler) {
    if (!(handler instanceof Function)) {
      throw new Error(`handler is not a function`);
    }
    if (!this.eventMap[type]) {
      this.eventMap[type] = [];
    }
    this.eventMap[type].push(handler);
  }
  emit(type, params) {
    if (this.eventMap[type]) {
      this.eventMap[type].forEach((handler) => {
        handler(params);
      });
    }
  }
  off(type, handler) {
    if (this.eventMap[type]) {
      this.eventMap[type].splice(this.eventMap[type].indexOf(handler), 1);
    }
  }
}

const eve = new EventEmitter();
const study = (params) =>
  console.log(`study has been emit, the params is ${params}`);
const sport = (params) =>
  console.log(`sport has been emit, the params is ${params}`);

eve.on('hobby', study);
eve.on('hobby', sport);
eve.emit('hobby', 'hello');
eve.off('hobby', study);
console.log(eve.eventMap);