釋出訂閱模式

冰凉小手發表於2024-03-20

概述

釋出-訂閱模式其實是一種物件間一對多的依賴關係,當一個物件的狀態傳送改變時,所有依賴於它的物件都將得到狀態改變的通知。

訂閱者(Subscriber)把自己想訂閱的事件註冊(Subscribe)到排程中心(Event Channel),當釋出者(Publisher)釋出該事件(Publish Event)到排程中心,也就是該事件觸發時,由排程中心統一排程(Fire Event)訂閱者註冊到排程中心的處理程式碼。

程式碼實現

class EventChannel {
  private handles: { [key: string]: Function[] } = {}
  on(event: string, callback: (...args: any[]) => void) {
    if (!this.handles[event]) this.handles[event] = []
    if (!this.handles[event].includes(callback)) this.handles[event].push(callback)
  }

  once(event: string, callback: (...args: any[]) => void) {
    function fn(this: EventChannel, ...args: any[]) {
      callback.apply(this, args)
      this.off(event, fn)
    }
    this.on(event, fn)
  }

  off(event: string, callback: Function) {
    if (this.handles[event]) {
      const index = this.handles[event].findIndex(fn => fn === callback)
      index > -1 && this.handles[event].splice(index, 1)
    }
  }

  emit(event: string, ...args: any[]) {
    if (this.handles[event]) {
      this.handles[event].forEach(fn => {
        fn.apply(this, args)
      })
    }
  }
}

應用場景

  • vue元件通訊事件匯流排

相關文章