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.
The event type to publish
Optional
event: anyOptional event data to pass to all handlers
The number of subscribers that were scheduled to be called
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.
The event type to publish
Optional
event: anyOptional event data to pass to all handlers
The number of subscribers that were called
Subscribe to an event type with a handler function
The event type to subscribe to (string or symbol)
The callback function to execute when the event is published
The index of the subscriber in the array, used for unsubscription
Unsubscribe a specific handler by its index
The event type to unsubscribe from
The index of the subscriber to remove (returned from subscribe)
Remove all subscribers for a specific event type
The event type to clear all subscribers from
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.
Example