My current setup involves an event dispatcher class that triggers listeners on specified occurrences. I've successfully implemented registering event listeners via decorators, but I feel like there may be a better solution out there.
At the moment, event listeners are gathered in a global registry and then registered with the event dispatcher. Simplified, my decorator looks like this:
// Decorator
export const EventListener = (events: string[]) => {
return (target: Type<object>): void => {
EventListenerRegistry.set(target);
};
};
// Listener example
@EventListener(['start'])
class OnStart {
public handle() {
}
}
With this setup, the OnStart
listener is activated when the start
event occurs.
One aspect of this approach that bothers me is the requirement for the EventListenerRegistry
, which appears as follows:
export const EventListenerRegistry = (new class {
protected listeners = [];
public set(target) {
this.listeners.push(target);
}
});
Using the EventListenerRegistry
means importing the same instance throughout, giving it somewhat of a "singleton" behavior.
Since my listeners are loaded with require
via glob
, the current setup automatically registers them with the dispatcher without extra effort on my part.
Despite this convenience, I wonder if there's a cleaner alternative to using registry classes. Any suggestions?