forked from YoanMalaver/Platzi-media-player
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
52 lines (41 loc) · 1.07 KB
/
index.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 Observer {
update: (data: any) => void;
}
interface Subject {
subscribe: (observer: Observer) => void;
unsubscribe: (observer: Observer) => void;
}
class BitcoinPrice implements Subject {
observers: Observer[] = [];
constructor() {
const el: HTMLInputElement = document.querySelector('#value');
el.addEventListener('input', () => {
this.notify(el.value);
});
}
subscribe(observer: Observer) {
this.observers.push(observer);
}
unsubscribe(observer: Observer) {
const index = this.observers.findIndex((obs) => {
return obs === observer;
});
this.observers.splice(index, 1);
}
notify(data: any) {
this.observers.forEach((observer) => observer.update(data));
}
}
class PriceDisplay implements Observer {
private el: HTMLElement;
constructor() {
this.el = document.querySelector('#price');
}
update(data: any) {
this.el.innerText = data;
}
}
const value = new BitcoinPrice();
const display = new PriceDisplay();
value.subscribe(display);
setTimeout(() => value.unsubscribe(display), 5000);