发布订阅模式
发布订阅模式其实是一种对象间一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都将得到状态改变的通知
它在代码中有很多应用比如,在Vue中的$on
、$off
,JS中经典的事件监听器······
document.body.addEventListener('click',
function(){console.log('123')}
);
//document.body充当了发布者的角色,它负责触发事件并通知所有订阅了该事件的对象;而绑定的函数则充当了订阅者的角色,它们订阅了点击事件,并在事件发生时执行相应的操作。
手写发布订阅
const MyEventBus = {
eventBus: {},
on(eventName, eventCallbackFn, thisArg = this) {
let handlers = this.eventBus[eventName]
if (!handlers) {
handlers = []
this.eventBus[eventName] = handlers
}
handlers.push(
{
eventCallbackFn,
thisArg
}
)
},
off(eventName, eventCallbackFn) {
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.eventCallbackFn === eventCallbackFn) {
const index = handlers.indexOf(handler)
handlers.splice(index, 1)
}
}
},
emit(eventName, ...payload) {
const handlers = this.eventBus[eventName]
if (!handlers) return;
handlers.map(handler => {
handler.eventCallbackFn.apply(handler.thisArg, payload)
})
}
}
结束了,希望对你有所帮助