发布订阅模式

373 阅读1分钟

发布订阅模式

class Event {
  constructor() {
    this.clientList = {};
  }

  listen(key, fn) {
    if (!this.clientList[key]) {
      this.clientList[key] = [];
    }
    this.clientList[key].push(fn);
  }

  trigger(key, ...args) {
    if (!this.clientList[key] || this.clientList[key].length === 0) {
      return false;
    }
    this.clientList[key].forEach(fn => {
      fn.apply(this, args);
    });
  }

  remove(key, fn) {
    if (!this.clientList[key] || this.clientList[key].length === 0) {
      return false;
    }
    if (!fn) {
      this.clientList[key].length = 0; // 如果不传fn 则移除所有监听事件
    }
    this.clientList[key] = this.clientList[key].filter(f => f === fn);
  }
}

const DEvent = new Event();
const fn1 = function(price) { // 小红订阅消息
  console.log('价格= ' + price); // 输出:'价格=2000000'
};
DEvent.listen('squareMeter88', fn1);
DEvent.listen('squareMeter88', function(price) { // 小红订阅消息
  console.log('价格1= ' + price); // 输出:'价格=2000000'
});
DEvent.trigger('squareMeter88', 3000000);// 售楼处发布消息

DEvent.remove('squareMeter88', fn1);
DEvent.trigger('squareMeter88', 4000000);// 售楼处发布消息