Created
July 30, 2024 15:54
-
-
Save satyam4p/6aa5701ff8388be714718eee49b06a72 to your computer and use it in GitHub Desktop.
event bus for custom events and handlers
This file contains 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 { | |
static handlers = {}; | |
static on(eventName, handler, scope) { | |
if (!EventBus.handlers[eventName]) { | |
EventBus.handlers[eventName] = []; | |
} | |
EventBus.handlers[eventName].push({ | |
subscription: handler, | |
scope, | |
}); | |
} | |
static fireEvent(eventName, ...args) { | |
if (!EventBus.handlers[eventName]) { | |
console.warn("Event is not registed."); | |
return; | |
} | |
const handlers = EventBus.handlers[eventName]; | |
for (let { subscription, scope } of handlers) { | |
scope = scope !== undefined ? scope : this; | |
subscription.apply(scope, args); | |
} | |
} | |
} | |
export default EventBus; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment