Given a need for a class to emit multi-listener events with typed payloads, and the following restrictions:
- No ability to inherit a different class, like what the Node.js
EventEmitter
requires (the class in question alreadyextends
something, and there's no possibility to create a mixin in ES6) - A need for encapsulation, in the way that only if the listener has a direct reference to the object, can it listen to its events (i.e. no global access to listen to the event, like what using standard JS/TS
CustomEvent
would result in) - Ability to listen to an event per-object (i.e. only on a specific instance of the class, not based on an event's string identifier - again the only thing that using
CustomEvent
would allow)
, what is the best approach/package/API to use?
Essentially, what I am looking for is something like this:
/** There is a class called ProcessDoer, which does some kind of work,
and emits an event once in a while, when the process is done
(in this example it's just an interval for simplicity).
It has a member variable onProcessDone, which is an event,
the class of which I would either want to write,
or if something like this exists in an npm package, know its name. */
class BaseClass {
public someProperty: number;
}
class ProcessDoer extends BaseClass {
constructor() {
super();
setInterval(() => {
this.someProperty = Math.random();
this.onProcessDone.emit(this.someProperty);
}, 1000);
}
public onProcessDone: SomeTypeOfEventEmitter<{ result: number }>;
}
const processDoer1 = new ProcessDoer();
const processDoer2 = new ProcessDoer();
/** In the example, the non-existent `SomeEventEmitterType` has a very
similar structure to `CustomEvent`, i.e. it's declared in a templated way,
with a specific payload variable name and type.
However, the callback isn't registered in a global way, like
`addEventListener`, but specifically on the exact instance needed. */
processDoer2.onProcessDone.addCallback((result: number) => {
console.log("The second ProcessDoer finished process with result", result);
});