Skip to content

Instantly share code, notes, and snippets.

@satyam4p
Created July 30, 2024 15:54
Show Gist options
  • Save satyam4p/6aa5701ff8388be714718eee49b06a72 to your computer and use it in GitHub Desktop.
Save satyam4p/6aa5701ff8388be714718eee49b06a72 to your computer and use it in GitHub Desktop.
event bus for custom events and handlers
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