game-engine/modules/event-emitter.js

32 lines
720 B
JavaScript

class EventEmitterSingleton {
static instance;
eventEmitter;
constructor() {
this.eventEmitter = {};
}
static getInstance() {
if (!EventEmitterSingleton.instance) {
EventEmitterSingleton.instance = new EventEmitterSingleton();
}
return EventEmitterSingleton.instance;
}
on(eventName, callback) {
if (!this.eventEmitter[eventName]) {
this.eventEmitter[eventName] = [];
}
this.eventEmitter[eventName].push(callback);
}
emit(eventName, ...args) {
if (this.eventEmitter[eventName]) {
this.eventEmitter[eventName].forEach((callback) => {
callback(...args);
});
}
}
}
export const eventEmitter = EventEmitterSingleton.getInstance();