-
Notifications
You must be signed in to change notification settings - Fork 0
/
signals_v2.js
86 lines (68 loc) · 1.66 KB
/
signals_v2.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
76
77
78
79
80
81
82
83
84
85
86
// Global variable to keep track of the currently accessed computed value
let currentComputed = null;
class Signal {
constructor(initialValue) {
this._value = initialValue;
this._dependents = [];
}
get value() {
if (currentComputed) {
this._addDependent(currentComputed);
}
return this._value;
}
set value(newValue) {
if (this._value !== newValue) {
this._value = newValue;
this._notifyDependents();
}
}
_addDependent(computed) {
if (!this._dependents.includes(computed)) {
this._dependents.push(computed);
}
}
_notifyDependents() {
for (const dependent of this._dependents) {
dependent._update();
}
}
}
class Computed {
constructor(computeFn) {
this._computeFn = computeFn;
this._value = undefined;
this._isStale = true;
}
get value() {
if (this._isStale) {
currentComputed = this;
this._recomputeValue();
currentComputed = null;
}
return this._value;
}
_recomputeValue() {
this._value = this._computeFn();
this._isStale = false;
}
_update() {
this._isStale = true;
}
}
function createSignal(initialValue) {
return new Signal(initialValue);
}
function createComputed(computeFn) {
return new Computed(computeFn);
}
// Creating signals
const count = createSignal(0);
const multiplier = createSignal(2);
// Creating a computed value
const multipliedCount = createComputed(() => count.value * multiplier.value);
console.log(multipliedCount.value); // 0
count.value = 2;
console.log(multipliedCount.value); // 4
multiplier.value = 3;
console.log(multipliedCount.value); // 6