hex-world
    Preparing search index...

    Class Emitter<EventMap>

    A small typed event emitter, generic over an event map — an interface whose keys are event names and whose values are that event's payload type:

    interface MyEvents {
    ready: { at: number };
    failed: Error;
    }
    const events = new Emitter<MyEvents>();
    events.on('ready', e => console.log(e.at)); // e is { at: number }
    events.emit('failed', new Error('nope'));

    Two behaviours matter for anything driven from a render loop:

    • Dispatch is snapshotted. emit iterates a copy of the listener set, so a listener that subscribes or unsubscribes while the event is being delivered doesn't change who receives this event. Without it, a handler that removes itself would make the iterator skip the next listener.
    • A throwing listener doesn't stop the others. One consumer's bug should not halt chunk streaming or drop the remaining subscribers' events. The error is still surfaced, not swallowed: by default it is rethrown from a microtask, which reaches window.onerror / unhandledException with its original stack. Set onError to route it somewhere else instead.

    Type Parameters

    • EventMap
    Index

    Constructors

    Properties

    onError: ((error: unknown, type: keyof EventMap) => void) | null = null

    Called when a listener throws, instead of the default asynchronous rethrow. Set this to log, count, or fail loudly in tests.

    Methods

    • Subscribe to an event. Returns an unsubscribe function, so a consumer can hold one disposer rather than keeping the listener reference around:

      const off = world.events.on('cellClick', onClick);
      // later
      off();

      Adding the same listener twice is a no-op — listeners are a set, so an event is never delivered to the same function twice.

      Type Parameters

      • K extends string | number | symbol

      Parameters

      Returns Unsubscribe

    • Unsubscribe a listener. Accepts either the function passed to on or the one passed to once (its wrapper is matched for you).

      Type Parameters

      • K extends string | number | symbol

      Parameters

      Returns void

    • Deliver an event to every current listener. Returns true if anyone was listening — useful to skip building an expensive payload:

      if (events.listenerCount('chunkLoaded') > 0) events.emit('chunkLoaded', buildPayload());
      

      Type Parameters

      • K extends string | number | symbol

      Parameters

      Returns boolean

    • How many listeners are subscribed to an event — 0 if none.

      Type Parameters

      • K extends string | number | symbol

      Parameters

      • type: K

      Returns number

    • Drop every listener for one event type, or (with no argument) for all of them.

      Type Parameters

      • K extends string | number | symbol

      Parameters

      • Optionaltype: K

      Returns void