Files
OpenFrontIO/src/core/EventBus.ts
T
Scott Anderson be01b90b25 Eslint (#998)
## Description:

Enable a few eslint rules:
- `@typescript-eslint/no-empty-object-type`
- `@typescript-eslint/no-require-imports`
- `no-useless-escape`

## Please complete the following:

- [x] I have added screenshots for all UI updates
- [x] I process any text displayed to the user through translateText()
and I've added it to the en.json file
- [x] I have added relevant tests to the test directory
- [x] I confirm I have thoroughly tested these changes and take full
responsibility for any bugs introduced
- [x] I understand that submitting code with bugs that could have been
caught through manual testing blocks releases and new features for all
contributors

---------

Co-authored-by: Scott Anderson <scottanderson@users.noreply.github.com>
2025-07-15 00:41:24 -04:00

45 lines
1.2 KiB
TypeScript

export type GameEvent = object;
export interface EventConstructor<T extends GameEvent = GameEvent> {
new (...args: any[]): T;
}
export class EventBus {
private listeners: Map<EventConstructor, Array<(event: GameEvent) => void>> =
new Map();
emit<T extends GameEvent>(event: T): void {
const eventConstructor = event.constructor as EventConstructor<T>;
const callbacks = this.listeners.get(eventConstructor);
if (callbacks) {
for (const callback of callbacks) {
callback(event);
}
}
}
on<T extends GameEvent>(
eventType: EventConstructor<T>,
callback: (event: T) => void,
): void {
if (!this.listeners.has(eventType)) {
this.listeners.set(eventType, []);
}
const callbacks = this.listeners.get(eventType)!;
callbacks.push(callback as (event: GameEvent) => void);
}
off<T extends GameEvent>(
eventType: EventConstructor<T>,
callback: (event: T) => void,
): void {
const callbacks = this.listeners.get(eventType);
if (callbacks) {
const index = callbacks.indexOf(callback as (event: GameEvent) => void);
if (index > -1) {
callbacks.splice(index, 1);
}
}
}
}