Skip to content

Instantly share code, notes, and snippets.

@vv13
Created Nov 30, 2021
Embed
What would you like to do?
[JS] A Simple EventBus
class EventBus {
constructor() {
this.eventMap = {}
this.onceEventMap = {}
}
on(eventName, listener) {
if (!this.eventMap[eventName]) {
this.eventMap[eventName] = [listener]
} else {
this.eventMap[eventName].push(listener)
}
}
emit(eventName, ...args) {
const listeners = this.eventMap[eventName] || []
listeners.forEach((listener) => listener.apply(null, args))
if (this.onceEventMap[eventName]) {
this.off(eventName, this.onceEventMap[eventName])
}
}
off(eventName, listener) {
if (!this.eventMap[eventName]) {
return
}
if (this.eventMap[eventName].length === 1 || !listener) {
delete this.eventMap[eventName]
return
}
this.eventMap[eventName] = this.eventMap[eventName].filter(
(item) => item !== listener
)
}
once(eventName, listener) {
this.on(eventName, listener)
this.onceEventMap[eventName] = listener
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment