-
Notifications
You must be signed in to change notification settings - Fork 0
/
signals_v1.js
75 lines (57 loc) · 1.41 KB
/
signals_v1.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
class Signal {
constructor(initialValue) {
this._value = initialValue;
this._dependents = new Set();
}
get value() {
return this._value;
}
set value(newValue) {
if (this._value !== newValue) {
this._value = newValue;
this._notifyDependents();
}
}
_notifyDependents() {
for (const dependent of this._dependents) {
dependent._update();
}
}
_addDependent(dependent) {
this._dependents.add(dependent);
}
}
class Computed {
constructor(computeFn, dependencies) {
this._computeFn = computeFn;
this._dependencies = dependencies;
this._value = undefined;
this._isStale = true;
for (const dependency of this._dependencies) {
dependency._addDependent(this);
}
}
get value() {
if (this._isStale) {
this._recomputeValue();
}
return this._value;
}
_recomputeValue() {
this._value = this._computeFn();
this._isStale = false;
}
_update() {
this._isStale = true;
}
}
// Creating signals
const count = new Signal(0);
const multiplier = new Signal(2);
// Creating a computed value
const multipliedCount = new Computed(() => count.value * multiplier.value, [count, multiplier]);
console.log(multipliedCount.value); // 0
count.value = 4;
console.log(multipliedCount.value); // 8
multiplier.value = 5;
console.log(multipliedCount.value); // 20