簡單的發(fā)布訂閱

class EventBus {
  constructor() {
    // eventMap 用來存儲事件和監(jiān)聽函數(shù)之間的關(guān)系
    this.eventMap = {};
  }
  // type 這里就代表事件的名稱
  on(type, handler) {
    // hanlder 必須是一個函數(shù),如果不是直接報錯
    if (!(handler instanceof Function)) {
      throw new Error("哥 你錯了 請傳一個函數(shù)");
    }
    // 判斷 type 事件對應的隊列是否存在
    if (!this.eventMap[type]) {
      // 若不存在,新建該隊列
      this.eventMap[type] = [];
    }
    // 若存在,直接往隊列里推入 handler
    this.eventMap[type].push(handler);
  }
  // 別忘了我們前面說過觸發(fā)時是可以攜帶數(shù)據(jù)的,params 就是數(shù)據(jù)的載體
  emit(type, params) {
    // 假設該事件是有訂閱的(對應的事件隊列存在)
    if (this.eventMap[type]) {
      // 將事件隊列里的 handler 依次執(zhí)行出隊
      this.eventMap[type].forEach((handler, index) => {
        // 注意別忘了讀取 params
        handler(params);
      });
    }
  }
  off(type, handler) {
    if (this.eventMap[type]) {
      this.eventMap[type].splice(this.eventMap[type].indexOf(handler) >>> 0, 1);
    }
  }
}

export default EventBus;

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容