Event publish-subscribe system implementation

This class provides a centralized event system where components can subscribe to events and publish events to notify subscribers. It supports both synchronous and asynchronous event publishing patterns.

const eventSystem = new EventPubSub();

// Subscribe to an event
const index = eventSystem.subscribe('user-login', (userData) => {
console.log('User logged in:', userData);
});

// Publish an event
eventSystem.publishSync('user-login', { userId: 123, name: 'John' });

// Unsubscribe
eventSystem.unsubscribe('user-login', index);

Implements

Constructors

Methods

  • Publish an event asynchronously to all subscribers

    Each subscriber is called asynchronously using setTimeout, allowing the current execution context to complete before handlers are invoked. This prevents blocking the main thread and allows for better performance in scenarios with many subscribers.

    Parameters

    • type: EventType

      The event type to publish

    • Optionalevent: any

      Optional event data to pass to all handlers

    Returns number

    The number of subscribers that were scheduled to be called

    const count = eventPubSub.publishAsync('user-action', { action: 'click', target: 'button' });
    console.log(`Scheduled ${count} handlers`);
  • Publish an event synchronously to all subscribers

    All subscribers are called immediately in the order they were registered. This method blocks until all handlers have completed execution.

    Parameters

    • type: EventType

      The event type to publish

    • Optionalevent: any

      Optional event data to pass to all handlers

    Returns number

    The number of subscribers that were called

    const count = eventPubSub.publishSync('data-changed', newData);
    console.log(`Called ${count} handlers synchronously`);
  • Subscribe to an event type with a handler function

    Parameters

    • type: EventType

      The event type to subscribe to (string or symbol)

    • handler: EventHandler

      The callback function to execute when the event is published

    Returns number

    The index of the subscriber in the array, used for unsubscription

    const index = eventPubSub.subscribe('data-updated', (data) => {
    console.log('Data changed:', data);
    });
  • Unsubscribe a specific handler by its index

    Parameters

    • type: EventType

      The event type to unsubscribe from

    • index: number

      The index of the subscriber to remove (returned from subscribe)

    Returns void

    const index = eventPubSub.subscribe('my-event', handler);
    eventPubSub.unsubscribe('my-event', index);