This repository was archived by the owner on Oct 18, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathobservable.ts
59 lines (48 loc) · 1.47 KB
/
observable.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
import { Logger } from './logger';
import { Observer } from './observer';
export abstract class Observable {
protected abstract logger: Logger;
protected observers: Record<string, Observer> = {};
/**
* @function subscribe
* @description Subscribe to an event
* @param type - event type
* @param listener - event callback
* @returns {void}
*/
public subscribe = (type: string, listener: Function): void => {
this.logger.log(`subscribed to ${type} event`);
if (!this.observers[type]) {
this.observers[type] = new Observer({ logger: this.logger });
}
this.observers[type].subscribe(listener);
};
/**
* @function unsubscribe
* @description Unsubscribe from an event
* @param type - event type
* @returns {void}
*/
public unsubscribe = (type: string, callback?: (data: unknown) => void): void => {
this.logger.log(`unsubscribed from ${type} event`);
if (!this.observers[type]) return;
if (!callback) {
this.observers[type].destroy();
delete this.observers[type];
return;
}
this.observers[type].unsubscribe(callback);
};
/**
* @function publish
* @description Publish an event to client
* @param type - event type
* @param data - event data
* @returns {void}
*/
protected publish = (type: string, data?: unknown): void => {
const hasListenerRegistered = type in this.observers;
if (!hasListenerRegistered) return;
this.observers[type].publish(data);
};
}