(前端)「中介者」設計模式在項目開發中的應用

  1. 事件起因

    事情是這樣的,我之前在做一個仿網易雲的項目,想實現一個功能,就是點擊歌曲列表組件(MusicList)中每一個item時,底部播放欄(FooterMusic)就能夠獲取我所點擊的這首歌曲的所有資訊(如圖1到圖2),但是底部播放欄是直接放在外殼組件App.vue中固定定位的,歌曲列表組件是作為頁面級組件HomeView.vue的子組件,因此他們二者至多只能算是兄弟組件(可能還差了一個輩分?),這就涉及到了兄弟組件之間的通訊問題。

 

  

        圖1                      圖2

  Vue2中實現兄弟組件的通訊一般是安裝EventBus插件,或者實例化一個Vue,它上面有關於事件的發布和訂閱方法,Vue3的話好像是使用mitt插件吧,但我不想用mitt,也不想裝插件,因此決定手寫一個EventBus。

 

2. 解決方案

  利用「中介者」設計模式。

  實現思路: 手寫一個EventBus,讓其作為中介者進行事件的發布與訂閱(或取消訂閱),在組件中調用EventBus實例進行事件的發布或訂閱即可。

  程式碼如下:

  src/EventBus/index.ts:

class EventBus {
  static instance: object;
  eventQueue: any

  constructor() {
    this.eventQueue = {}
  }

  // 用單例模式設計一下,使全局只能有一個EventBus實例,這樣調度中心eventQueue就唯一了,所有事件與其對應的訂閱者都在裡面
  static getInstance() {
    if(!EventBus.instance) {
      Object.defineProperty(EventBus, 'instance', {
        value: new EventBus()
      });
    }

    return EventBus.instance;
  }

  // 事件發布
  $emit(type: string, ...args: any[]) {
    if(this.eventQueue.hasOwnProperty(type)) {
      // 如果調度中心中已包含此事件, 則直接將其所有的訂閱者函數觸發
      this.eventQueue[type].forEach((fn: Function) => {
        fn.apply(this, args);
      });
    }
  }


  // 事件訂閱
  $on(type: string, fn: Function) {
    if(!this.eventQueue.hasOwnProperty(type)) {
      this.eventQueue[type] = [];
    }
    
    if(this.eventQueue[type].indexOf(fn) !== -1) {
      // 說明該訂閱者已經訂閱過了
      return;
    }
    this.eventQueue[type].push(fn);
  }


  // 取消事件訂閱, 將相應的回調函數fn所在的位置置為null即可
  $off(type: string, fn: Function) {
    if(this.eventQueue.hasOwnProperty(type)) {
      this.eventQueue[type].forEach((item: Function, index: number) => {
        if(item == fn) {
          this.eventQueue[type][index] = null;
        }
      });
    }
  }
}



// 最後導出單例的時候記得給單例斷言成any哈, 要不然在組件內調用eventBus.$on('xxx', () => {...})會報錯對象上沒有$on這個方法
export default EventBus.getInstance() as any;

 

  寫好了中介者之後,我們在組件中使用一下

  在歌曲列表組件中點擊事件後觸發 

eventBus.$emit(‘CUR_SONG’, curSongMsg);  進行事件的發布,並帶上歌曲資訊

  

  在底部播放欄組件中訂閱這個事件

eventBus.$on('CUR_SONG', (curSongMsg: IMusic) => {
    console.log('訂閱事件: CUR_SONG');
    console.log('curSongMsg: ', curSongMsg);

    // reactive定義的引用類型必須逐個屬性進行賦值才能實現頁面的響應式更新
    songMsg.name = curSongMsg.name;
    songMsg.author = curSongMsg.author;
    songMsg.mv = curSongMsg.mv;
});

 

  以上就完成了利用中介者EventBus進行事件的發布與訂閱,實現無關組件之間的通訊問題。

  

  參考書籍 《JavaScript設計模式》 張容銘 著