生活随笔
收集整理的這篇文章主要介紹了
手写实现简单的Vue事件总线
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一、什么是事件總線
自定義事件總線屬于一種觀察者模式,其中包括三個角色:
- 發布者(Publisher):發出事件(Event);
- 訂閱者(Subscriber):訂閱事件(Event),并且會進行響應(Handler);
- 事件總線(EventBus):無論是發布者還是訂閱者都是通過事件總線作為中臺的;
當然我們可以選擇一些第三方的庫:
- Vue2默認是帶有事件總線的功能;
- Vue3中推薦一些第三方庫,比如mitt;
二、手寫實現事件總線
當然我們也可以實現自己的事件總線:
- 事件的監聽方法on:存儲對應事件名需要執行的事件函數
- 事件的發射方法emit:執行對應事件名需要執行的事件函數
- 事件的取消監聽off:刪除對應事件名需要執行的事件函數
運行結果:
class EventBus {constructor() {this.eventBus
= {}}on(eventName
, eventCallback
, thisArg
) {let handlers
= this.eventBus
[eventName
]if (!handlers
) {handlers
= []this.eventBus
[eventName
] = handlers
}handlers
.push({eventCallback
,thisArg
})}emit(eventName
, ...payload
) {const handlers
= this.eventBus
[eventName
]if (!handlers
) returnhandlers
.forEach(handler
=> {handler
.eventCallback
.apply(handler
.thisArg
, payload
)})}off(eventName
, eventCallback
) {const handlers
= this.eventBus
[eventName
]if (!handlers
) returnconst newHandlers
= [...handlers
]for (let i
= 0; i
< newHandlers
.length
; i
++) {const handler
= newHandlers
[i
]if (handler
.eventCallback
=== eventCallback
) {const index
= handlers
.indexOf(handler
)handlers
.splice(index
, 1)}}}
}
const eventBus
= new EventBus()
eventBus
.on('abc', function (payload
) {console
.log('監聽abc事件', this, payload
)
}, {name
: 'zep'})const handleCallback = function (payload
) {console
.log('監聽abc事件', this, payload
)
}
eventBus
.on('abc', handleCallback
, {name
: 'lala'})
eventBus
.emit('abc', 123)eventBus
.off('abc', handleCallback
)
eventBus
.emit('abc', 123)
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎
總結
以上是生活随笔為你收集整理的手写实现简单的Vue事件总线的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。