Improve event emitter

This commit is contained in:
Olivier Gagnon
2021-09-18 15:44:39 -04:00
parent 4b6a6300f5
commit 61e3959a25
15 changed files with 46 additions and 61 deletions
+21 -21
View File
@@ -17,33 +17,33 @@ export interface ISubscriber {
id: string;
}
export class EventEmitter {
/**
* Map of Subscriber name -> Callback function
*/
subscribers: IMap<cbFn> = {};
function uuidv4(): string {
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
var r = (Math.random() * 16) | 0,
v = c == "x" ? r : (r & 0x3) | 0x8;
return v.toString(16);
});
}
constructor(subs?: ISubscriber[]) {
if (Array.isArray(subs)) {
for (const s of subs) {
this.addSubscriber(s);
}
}
export class EventEmitter<T extends any[]> {
subscribers: { [key: string]: (...args: [...T]) => void | undefined } = {};
subscribe(s: (...args: [...T]) => void): () => void {
let uuid = uuidv4();
while (this.subscribers[uuid] !== undefined) uuid = uuidv4();
this.subscribers[uuid] = s;
return () => {
delete this.subscribers[uuid];
};
}
addSubscriber(s: ISubscriber): void {
this.subscribers[s.id] = s.cb;
}
emitEvent(...args: any[]): void {
emit(...args: [...T]): void {
for (const s in this.subscribers) {
const sub = this.subscribers[s];
if (sub === undefined) continue;
sub(args);
sub(...args);
}
}
removeSubscriber(id: string): void {
delete this.subscribers[id];
}
}