手写时间简易版事件总线
自定义事件总线属于一种观察者模式,其中包括三个角色:
发布者(Publisher):发出事件(Event);
订阅者(Subscriber):订阅事件(Event),并且会进行响应(Handler);
事件总线(EventBus):无论是发布者还是订阅者都是通过事件总线作为中台的;
当然我们可以选择一些第三方的库:
Vue2默认是带有事件总线的功能;
Vue3中推荐一些第三方库,比如mitt;
当然我们也可以实现自己的事件总线:
事件的监听方法on;
事件的发射方法emit;
事件的取消监听off;
class DYEventBus {
constructor() {
this.eventBus = {}
}
on(eventName, eventCallback, thisArg) {
let handlers = this.eventBus[eventName]
if (!handlers) {
handlers = []
this.eventBus[eventName] = handlers
}
handlers.push({
eventCallback,
thisArg
})
}
off(eventName, eventCallback) {
const handlers = this.eventBus[eventName]
if (!handlers) return
const 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)
}
}
}
emit(eventName, ...payload) {
const handlers = this.eventBus[eventName]
if (!handlers) return
handlers.forEach((handler) => {
handler.eventCallback.apply(handler.thisArg, payload)
})
}
}
const eventBus = new DYEventBus()
// main.js
eventBus.on(
'abc',
function () {
console.log('监听abc1', this, arguments)
},
{ name: 'zdy' }
)
const handleCallback = function (...args) {
console.log('监听abc2', this, args)
// console.log(args)
}
eventBus.on('abc', handleCallback, { name: 'why' })
// utils.js
eventBus.emit('abc', 123, 234, 456)
// 移除监听
eventBus.off('abc', handleCallback)
eventBus.emit('abc', 123)



