Created
November 30, 2021 05:16
-
-
Save vv13/3a721d71ca93b18cdd3fd8b3edca01dc to your computer and use it in GitHub Desktop.
[JS] A Simple EventBus
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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