@needle-tools/engine
Version:
Needle Engine is a web-based runtime for 3D apps. It runs on your machine for development with great integrations into editors like Unity or Blender - and can be deployed onto any device! It is flexible, extensible and networking and XR are built-in.
47 lines • 1.45 kB
JavaScript
/** Typed event bus. Known {@link ContextEventMap} events get full autocomplete.
* Custom events can be typed at the call site via generic parameter.
* @example Known events
* ```ts
* context.events.on("scene-content-changed", e => e.object);
* ```
* @example Custom events — type at call site
* ```ts
* context.events.emit<{ pts: number }>("scored", { pts: 10 });
* context.events.on<{ pts: number }>("scored", e => e.pts);
* ```
* @example Once
* ```ts
* context.events.on("scene-content-changed", e => { ... }, { once: true });
* ```
*/
export class EventBus {
_listeners = new Map();
emit(type, detail) {
const arr = this._listeners.get(type);
if (arr)
for (const cb of [...arr])
cb(detail);
}
on(type, callback, options) {
let arr = this._listeners.get(type);
if (!arr) {
arr = [];
this._listeners.set(type, arr);
}
const unsub = () => {
const i = arr.indexOf(wrapped);
if (i >= 0)
arr.splice(i, 1);
};
const wrapped = options?.once
? (...args) => { unsub(); callback(...args); }
: callback;
arr.push(wrapped);
return unsub;
}
/** Remove all listeners. Called when the context is cleared or destroyed. */
clear() {
this._listeners.clear();
}
}
//# sourceMappingURL=engine_context_eventbus.js.map