You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
55 lines
1.4 KiB
55 lines
1.4 KiB
2 years ago
|
interface Type<T> extends Function {
|
||
|
new (...args: any[]): T;
|
||
|
}
|
||
|
|
||
|
export interface IEventProcessor {
|
||
|
processEvents: (events: any[]) => void;
|
||
|
}
|
||
|
|
||
|
export class EventProcessor {
|
||
|
private handlers = new Map();
|
||
|
|
||
|
static watch<T extends Type<{}>>(Base: T) {
|
||
|
const eventProcessor = new EventProcessor();
|
||
|
return class extends Base {
|
||
|
constructor(...args: any[]) {
|
||
|
super(...args);
|
||
|
const methods = Base.prototype["eventProcessorMethods"] || new Map();
|
||
|
for (const [eventType, handler] of methods) {
|
||
|
eventProcessor.setHandler(eventType, handler.bind(this));
|
||
|
}
|
||
|
}
|
||
|
processEvents(events: any[]) {
|
||
|
for (const event of events) {
|
||
|
eventProcessor.emit(event);
|
||
|
}
|
||
|
}
|
||
|
};
|
||
|
}
|
||
|
|
||
|
static handle<T>(eventType: Type<T>) {
|
||
|
return (
|
||
|
target: any,
|
||
|
_propertyKey: string,
|
||
|
descriptor: TypedPropertyDescriptor<(ev: T) => void>
|
||
|
) => {
|
||
|
if (!("eventProcessorMethods" in target)) {
|
||
|
target["eventProcessorMethods"] = new Map();
|
||
|
}
|
||
|
const methods = target["eventProcessorMethods"];
|
||
|
methods.set(eventType, descriptor.value);
|
||
|
};
|
||
|
}
|
||
|
|
||
|
setHandler<T>(GameEvent: Type<T>, handler: (gameEvent: T) => void) {
|
||
|
this.handlers.set(GameEvent, handler);
|
||
|
}
|
||
|
|
||
|
emit<T extends Object>(gameEvent: T) {
|
||
|
const handler = this.handlers.get(gameEvent.constructor);
|
||
|
if (handler !== undefined) {
|
||
|
handler(gameEvent);
|
||
|
}
|
||
|
}
|
||
|
}
|