Repository navigation
Open
Labels
Description
class EventBus {
constructor() {
this.eventBus = {}
}
on(eventName, eventCallback, thisArg) {
if (typeof eventName !== 'string') {
throw new TypeError('the event name must be string type')
}
if (typeof eventCallback !== 'function') {
throw new TypeError('the event callback must be function type')
}
let handlers = this.eventBus[eventName]
if (!handlers) {
handlers = []
this.eventBus[eventName] = handlers
}
handlers.push({
eventCallback,
thisArg
})
return this
}
off(eventName, eventCallback) {
if (typeof eventName !== 'string') {
throw new TypeError('the event name must be string type')
}
if (typeof eventCallback !== 'function') {
throw new TypeError('the event callback must be function type')
}
const handlers = this.eventBus[eventName]
if (handlers && eventCallback) {
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)
}
}
}
if (handlers.length === 0) {
delete this.eventBus[eventName]
}
}
once(eventName, eventCallback, thisArg) {
if (typeof eventName !== 'string') {
throw new TypeError('the event name must be string type')
}
if (typeof eventCallback !== 'function') {
throw new TypeError('the event callback must be function type')
}
const tempCallback = (...payload) => {
this.off(eventName, tempCallback)
eventCallback.apply(thisArg, payload)
}
return this.on(eventName, tempCallback, thisArg)
}
emit(eventName, ...payload) {
if (typeof eventName !== 'string') {
throw new TypeError('the event name must be string type')
}
const handlers = this.eventBus[eventName] || []
handlers.forEach((handler) => {
handler.eventCallback.apply(handler.thisArg, payload)
})
return this
}
}Reacted by BaboonKing and luckept
Activity
betteroneday commentedon Jun 9, 2022

看起来index这行代码似乎并不需要,index和i是一致的。handlers.splice(i, 1)Hongbusi commentedon Jun 10, 2022
使用
splice删除handlers一个元素之后,其他元素的下标可能会发生改变。@betteronedaybaboon-king commentedon Jun 10, 2022
mini 版来了
[-]手写事件总线[/-][+]手写题:事件总线[/+]lyx-jay commentedon Jun 10, 2022
简单版 EventBus