-
Notifications
You must be signed in to change notification settings - Fork 0
/
Subscriber.js
44 lines (40 loc) · 999 Bytes
/
Subscriber.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
38
39
40
41
42
43
44
export default class Subscriber {
constructor(data) {
this.value = data;
this.listeners = {};
}
/*
newValue = new the value of the subscriber.
trigger = should trigger the listeners.
Sets data and triggers listeners (optional).
*/
set(newValue, trigger = true) {
this.value = newValue;
if (trigger)
this.trigger();
}
/*
triggers the events but doesnt set data.
*/
trigger() {
let keys = Object.keys(this.listeners);
for (let i = 0; i < keys.length; i++) {
this.listeners[keys[i]].callback(this.value);
}
}
get() {
return this.value;
}
watch(callback) {
let token = {
id: Math.random().toString(),
callback,
stop: () => {
delete this.listeners[token.id];
}
}
this.listeners[token.id] = token;
callback(this.value);
return token;
}
}