-
Notifications
You must be signed in to change notification settings - Fork 0
/
signalis.ts
38 lines (34 loc) · 1.1 KB
/
signalis.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
export class Signalis {
private signals: {
callback: (...args: any[]) => void;
key: string;
}[] = [];
public connect<V>(signal: string, callback: (...args: V[]) => void) {
this.signals.push({
callback,
key: signal,
});
}
public waitFor<V>(signal: string): Promise<V> {
return new Promise((resolve) => {
this.connect(signal, resolve);
});
}
// Improved emit method with handler removal
public emit<V>(signal: string, ...args: V[]) {
this.signals = this.signals.filter(handler => {
const { key, callback } = handler;
if (key === signal) {
callback(...args);
return false; // Remove the handler after calling it
}
return true;
});
}
// New method to disconnect a specific handler
public disconnect<V>(signal: string, callback: (...args: V[]) => void) {
this.signals = this.signals.filter(handler => {
return handler.key !== signal || handler.callback !== callback;
});
}
}