blob: 938269728e50eb24898f2b217c17482510871cf2 (
plain) (
blame)
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
39
40
41
42
43
44
45
46
47
48
49
50
51
|
import type { UnsubscribeCallback } from "./types";
type Subscriber<T extends any[]> = (...payload: T) => void;
export class Emitter<T extends any[] = []> {
public subscribers: Subscriber<T>[] = [];
/**
* Attaches subscriber
*
* @returns unsubscribe function
*/
on(...handlers: Subscriber<T>[] | Subscriber<T>[][]): UnsubscribeCallback {
const _handlers = handlers
.flat()
.filter((item) => typeof item === "function");
this.subscribers.push(..._handlers);
return () => this.off(_handlers);
}
once(...handlers: Subscriber<T>[] | Subscriber<T>[][]): UnsubscribeCallback {
const _handlers = handlers
.flat()
.filter((item) => typeof item === "function");
_handlers.push(() => detach());
const detach = this.on(..._handlers);
return detach;
}
off(...handlers: Subscriber<T>[] | Subscriber<T>[][]) {
const _handlers = handlers.flat();
this.subscribers = this.subscribers.filter(
(handler) => !_handlers.includes(handler),
);
}
trigger(...payload: T) {
for (const handler of this.subscribers) {
handler(...payload);
}
return this;
}
clear() {
this.subscribers = [];
}
}
|