JS手寫代碼之發布訂閱模式


發布訂閱模式

發布訂閱模式的發布和訂閱都由一個調度中心來處理

發布訂閱模式是完全解耦的,因為調度中心中存的直接就是邏輯處理函數

要點:都要實現添加/刪除/派發更新三個事件。

class Event {
  // 首先定義一個事件容器,用來裝事件數組(因為訂閱者可以是多個)
  #handlers = {}

  // 事件添加方法,參數有事件名和事件方法
  addEventListener(type, handler) {
    // 首先判斷handlers內有沒有type事件容器,沒有則創建一個新數組容器
    if (!(type in this.#handlers)) {
      this.#handlers[type] = []
    }
    // 將事件存入
    this.#handlers[type].push(handler)
  }

  // 觸發事件兩個參數(事件名,參數)
  dispatchEvent(type, ...params) {
    // 若沒有注冊該事件則拋出錯誤
    if (!(type in this.#handlers)) {
      return new Error('未注冊該事件')
    }
    // 便利觸發
    this.#handlers[type].forEach(handler => {
      handler(...params)
    })
  }

  // 事件移除參數(事件名,刪除的事件,若無第二個參數則刪除該事件的訂閱和發布)
  removeEventListener(type, handler) {
    // 無效事件拋出
    if (!(type in this.#handlers)) {
      return new Error('無效事件')
    }
    if (!handler) {
      // 直接移除事件
      delete this.#handlers[type]
    } else {
      const idx = this.#handlers[type].findIndex(ele => ele === handler)
      // 拋出異常事件
      if (idx === -1) {
        return new Error('無該綁定事件')
      }
      // 移除事件
      this.#handlers[type].splice(idx, 1)
      if (this.#handlers[type].length === 0) {
        delete this.#handlers[type]
      }
    }
  }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM