-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathobserver.ts
52 lines (43 loc) · 1.05 KB
/
observer.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
interface ISubscriber {
update(observer: IObserver): void,
}
interface IObserver {
someLogic(): void,
notify(): void;
subscribe(subscriber: ISubscriber): void;
unsubscribe(subscriber: ISubscriber): void;
}
class Observer implements IObserver {
private subs: ISubscriber[] = [];
someLogic() {
console.log('some logic');
this.notify();
}
subscribe(subscriber: ISubscriber) {
this.subs.push(subscriber);
}
unsubscribe(subscriber: ISubscriber) {
this.subs.pop();
}
notify() {
this.subs.forEach((sub) => sub.update(this))
}
}
class Subs1 implements ISubscriber {
update(observer: IObserver) {
console.log('sub1 update', this)
}
}
class Subs2 implements ISubscriber {
update(observer: IObserver) {
console.log('sub2 update', this)
}
}
const observer = new Observer();
const subs1 = new Subs1();
const subs2 = new Subs2();
observer.subscribe(subs1);
observer.subscribe(subs2);
observer.someLogic();
observer.unsubscribe(subs2);
observer.someLogic();