hd-utils
Version:
A handy utils for modern JS developers
33 lines (26 loc) • 1.23 kB
TypeScript
import { EventCallback } from "../utils/types";
/**
* @description EventBus implementation for handling custom events within a JavaScript application. It enables communication between different modules by providing methods for subscribing to, unsubscribing from, and publishing events. This fosters a decoupled architecture, allowing components to exchange information and trigger actions based on custom events.
* @example
*
// Create an instance of the event bus
const eventBus = new EventBus();
// Subscribe to an event
function handleEvent1(data?: any) {
console.log('Event 1 handled with data:', data);
}
eventBus.subscribe('event1', handleEvent1);
// Publish an event
eventBus.publish('event1', { message: 'Hello, Event 1!' });
// Unsubscribe from an event
eventBus.unsubscribe('event1', handleEvent1);
// The following publish won't trigger the handleEvent1 function because it's unsubscribed
eventBus.publish('event1', { message: 'This will not be handled.' });
*/
export default class EventBus {
private listeners;
constructor();
subscribe(event: string, callback: EventCallback): void;
unsubscribe(event: string, callback: EventCallback): void;
publish(event: string, data?: any): void;
}