/
EventDispatcherBase.ts
84 lines (75 loc) · 2.03 KB
/
EventDispatcherBase.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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
export interface EventHandler<T> {
(value: T): any;
}
/**
* A base for dispatching {@link Subscribable}s.
*
* @typeParam TValue - The type of the argument passed to subscribers.
* @typeParam THandler - The type of the callback function.
*/
export abstract class EventDispatcherBase<
TValue,
THandler extends EventHandler<TValue> = EventHandler<TValue>,
> {
public readonly subscribable: Subscribable<TValue, THandler> =
new Subscribable(this);
private subscribers = new Set<THandler>();
/**
* {@inheritDoc Subscribable.subscribe}
*/
public subscribe(handler: THandler) {
this.subscribers.add(handler);
return () => this.unsubscribe(handler);
}
/**
* {@inheritDoc Subscribable.unsubscribe}
*/
public unsubscribe(handler: THandler) {
this.subscribers.delete(handler);
}
/**
* Unsubscribe all subscribers from the event.
*/
public clear() {
this.subscribers.clear();
}
protected notifySubscribers(value: TValue): ReturnType<THandler>[] {
return [...this.subscribers].map(handler => handler(value));
}
}
/**
* Provides safe access to the public interface of {@link EventDispatcherBase}.
*
* @remarks
* External classes can use it to subscribe to an event without being able to
* dispatch it.
*
* @typeParam TValue - The type of the argument passed to subscribers.
* @typeParam THandler - The type of the callback function.
*/
export class Subscribable<
TValue,
THandler extends EventHandler<TValue> = EventHandler<TValue>,
> {
public constructor(
protected dispatcher: EventDispatcherBase<TValue, THandler>,
) {}
/**
* Subscribe to the event.
*
* @param handler - The handler to invoke when the event occurs.
*
* @returns A callback function that cancels the subscription.
*/
public subscribe(handler: THandler) {
return this.dispatcher.subscribe(handler);
}
/**
* Unsubscribe from the event.
*
* @param handler - The handler to unsubscribe.
*/
public unsubscribe(handler: THandler) {
this.dispatcher.unsubscribe(handler);
}
}