-
Notifications
You must be signed in to change notification settings - Fork 0
/
Observable.js
37 lines (33 loc) · 880 Bytes
/
Observable.js
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
/*
curl https://raw.githubusercontent.com/voischev/tool/main/Observable.js > Observable.js
const user = new Observable(elem.innerHTML);
user.subscribe(() => {
elem.innerHTML = user.value
})
user.value = 'Ivan';
*/
class Observable {
#subscribers = [];
#value = null;
constructor(initialValue) {
this.#value = initialValue;
}
get value() {
return this.#value;
}
set value(value) {
this.#value = value;
this.#subscribers.forEach(callback => callback(value));
}
subscribe(callback) {
if (this.#subscribers.includes(callback) === false) {
this.#subscribers.push(callback);
}
}
unsubscribe(callback) {
const index = this.#subscribers.indexOf(callback);
if (index > -1) {
this.#subscribers = this.#subscribers.splice(index, 1);
}
}
}