I've created a class EventBus. This class provides an interface for attaching on/off/once methods to a class, the class extending it can in turn provide an array of possible events that can be listened to.
Currently, to make it work I need to extend the class with EventBus. I feel this isn't the right approach;
class Something extends EventBus {
private events: Array<string> = [
'ready',
];
constructor() {
this.registerEventBus(this.events);
}
}
EventBus is initialised using a method, not a constructor, though a constructor can also be used;
class EventBus {
private eventListeners: EventListeners = {};
registerEventBus(eventListenersArray: Array<string> = []) {
eventListenersArray.forEach((listener) => {
this.eventListeners[listener] = [];
});
}
...on, off, supporting private methods etc
I'm wondering what the right approach for this is. I feel extending something with EventBus isn't correct inheritance, EventBus is a dependency that's used. My issue is that events should be chainable, returning the correct context after each call;
const someInstance = new Something();
someInstance
.on('ready', () => {})
.on('destroyed', () => {});
Currently I struggle to find a solution to this that works with typescript, I know it should be injected but I fail to do so. If anyone know the correct term for the approach I should take, or a sample of code that I can use to circumvent the extends
, I would be very grateful!