??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.$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設計模式》 張容銘 著
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/501125.html
標籤:其他
下一篇:設計模式之橋接模式
