EventManager
import EventManager, { type EventMapBlank } from "@arclockproject/common/library/EventManager";
For examples and live demos, see the EventManager guide.
EventManager
Class · default export
class EventManager<EventMap extends EventMapBlank>
A typed event emitter. EventMap maps each event name to its listener's
signature, so dispatch and addListener are type-checked.
Constructor
new EventManager(defaults?: { [key in keyof EventMap]: EventMap[key][] })
Creates an event manager with no listeners, or with defaults.
Parameters
defaults?({ [key in keyof EventMap]: EventMap[key][] }) — Listeners to start with, per event. The arrays are used as they are, not copied, so adding or removing listeners to said array also changes them in EventManager.
Example
const events = new EventManager<{
pay: (client: string, amount: number) => void;
}>();
events.addListener("pay", (client, amount) => console.log(client, amount));
events.dispatch("pay", "Alex", 100); // logs "Alex 100"
EventManager.addListener()
EventManager.addListener<k extends keyof EventMap>(type: k, listener: EventMap[k]): EventMap[k]
Adds a listener for type. Adding the same listener twice makes it run twice.
Parameters
type(k) — Event name.listener(EventMap[k]) — Function to call when the event is dispatched.
Returns EventMap[k] — listener, so an inline function can be kept for removeListener.
EventManager.removeListener()
EventManager.removeListener<k extends keyof EventMap>(type: k, listener: EventMap[k]): void
Removes one registration of listener for type. Does nothing if it was not added.
Parameters
type(k) — Event name.listener(EventMap[k]) — The same function that was passed toaddListener.
EventManager.removeAllListeners()
EventManager.removeAllListeners<k extends keyof EventMap>(type: k): void
Removes every listener for type.
Parameters
type(k) — Event name.
EventManager.removeAll()
EventManager.removeAll(): void
Removes every listener for every event.
EventManager.dispatch()
EventManager.dispatch<k extends keyof EventMap>(type: k, ...payload: Parameters<EventMap[k]>): void
Calls every listener for type right away, in the order they were added.
Parameters
type(k) — Event name....payload(Parameters<EventMap[k]>) — Arguments passed to each listener.
EventMapBlank
Type
type EventMapBlank
The shape every event map must have: event names mapped to listener functions.
Properties
[key: string]((...any: any) => void)