#
EventBus
A basic implementation of a pub/sub mechanism enabling loosely coupled between the host application and the modules.
#
Reference
const eventBus = new EventBus(options?: { logger? })
#
Parameters
options
: An optional object literal of options:logger
: An optional logger to facilitate debugging.
#
Usage
#
Create an event bus instance
import { EventBus, ConsoleLogger } from "@squide/firefly";
const eventBus = new EventBus({
logger: new ConsoleLogger()
});
#
Add a listener
When possible, prefer useEventBusListener to eventBus.addListener
.
import { useCallback } from "react";
const handleFoo = useCallback((data, context) => {
// do something...
}, [];
// Listen to every "foo" events.
eventBus.addListener("foo", handleFoo);
// Listen to the first "foo" event, then automatically remove the listener.
eventBus.addListener("foo-once", handleFoo, { once: true });
#
Remove a listener
// Remove a regular listener.
eventBus.removeListener("foo", handleFoo);
// Remove a listener created with the `once` option.
eventBus.removeListener("foo-once", handleFoo, { once: true });
#
Dispatch an event
When possible, prefer useEventBusDispatcher to eventBus.dispatch
.
eventBus.dispatch("foo", "bar");