Event Bus
Lets game systems talk without knowing about each other: the score, sound and achievement code all listen for “enemy:killed” instead of the enemy calling them.
Files: event-bus.js (the component, no dependencies) and event-bus.test.mjs (5 tests).
Copy event-bus.js into your game, for example to src/components/, and import it as an ES module.
Usage
import { createEventBus } from "./event-bus.js";
export const events = createEventBus();
events.on("enemy:killed", ({ points }) => score.add(points));
events.on("enemy:killed", () => audio.play("pop"));
events.emit("enemy:killed", { points: 100 });
const off = events.on("level:start", start); off(); // stop listening
API
createEventBus({ onError }) → eventsevents.on(type, fn) → off()fn(payload, type)events.once(type, fn) → off()events.off(type, fn)events.onAny(fn) → off()every event, fn(type, payload) (handy for debugging and replays)events.emit(type, payload) → number of listeners calledevents.count(type) / events.clear(type?)
A listener that throws doesn’t stop the others; the error goes to onError (default console.error).
Listeners added or removed during an emit take effect from the next emit.
Engines
| Engine | Notes |
|---|---|
| Vanilla, Phaser, PixiJS, Three.js | yes. Phaser and Pixi have their own emitters; this one is engine-free so game logic stays portable. |
Tests
Node tests: order, payloads, once, off during emit, wildcard listeners, listener errors, counts.
Run them with node --test toolkit/components/event-bus/ (Node 20 or newer, nothing to install).