mirror of
https://github.com/bitburner-official/bitburner-src.git
synced 2026-04-26 03:00:56 +02:00
Improve event emitter
This commit is contained in:
+21
-21
@@ -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];
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user