Bin
2025-12-17 d616898802dfe7e5dd648bcf53c6d1f86b6d3642
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
52
53
54
55
import { Destructable } from "./Destructable";
 
type AnyFunction = (...args: any[]) => any;
 
type ToFunction<T> = T extends AnyFunction ? T : never;
 
export class Events<ET, ETS extends keyof ET = keyof ET> extends Destructable {
  private subscriptions = new Map<ETS, Set<any>>();
 
  on<T extends ETS>(eventName: T, handler: ET[T]) {
    const events = this.getSubscriptions(eventName);
 
    if (events.has(handler) === false) {
      events.add(handler);
    }
  }
 
  off<T extends ETS>(eventName: T, handler: ET[T]) {
    const events = this.getSubscriptions(eventName);
 
    if (events.has(handler)) {
      events.delete(handler);
    }
  }
 
  invoke<T extends ETS, ETF = ET[T]>(eventName: T, args?: Parameters<ToFunction<ETF>>) {
    const events = this.getSubscriptions(eventName);
 
    events.forEach((evt) => evt(...(args ?? [])));
  }
 
  removeAllListeners() {
    this.subscriptions.forEach((sub) => sub.clear());
    this.subscriptions.clear();
  }
 
  destroy(): void {
    this.removeAllListeners();
 
    this.on = () => null;
    this.off = () => null;
    this.invoke = () => null;
    this.removeAllListeners = () => null;
 
    super.destroy();
  }
 
  private getSubscriptions<T extends ETS>(eventName: T) {
    const events = this.subscriptions.get(eventName) ?? new Set<ET[T]>();
 
    this.subscriptions.set(eventName, events);
 
    return events;
  }
}