Open History to see the last commit
1type Listener = () => void
2β
3export class Subscribable<TListener extends Function = Listener> {
4 protected listeners: Set<{ listener: TListener }>
5β
6 constructor() {
7 this.listeners = new Set()
8 this.subscribe = this.subscribe.bind(this)
9 }
10β
11 subscribe(listener: TListener): () => void {
12 const identity = { listener }
13 this.listeners.add(identity)
14β
15 this.onSubscribe()
16β
17 return () => {
18 this.listeners.delete(identity)
19 this.onUnsubscribe()
20 }
21 }
22β
23 hasListeners(): boolean {
24 return this.listeners.size > 0
25 }
26β
27 protected onSubscribe(): void {
28 // Do nothing
29 }
30β
31 protected onUnsubscribe(): void {
32 // Do nothing
33 }
34}