Skip to content

Instantly share code, notes, and snippets.

@vv13
Created November 30, 2021 05:16
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
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