發佈訂閱模式

發佈訂閱模式

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);// 售樓處發佈消息
複製代碼
相關文章
相關標籤/搜索