-
Notifications
You must be signed in to change notification settings - Fork 0
/
signals_v3.js
107 lines (89 loc) · 1.95 KB
/
signals_v3.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
// Global variable to keep track of the currently accessed computed or effect
let currentAccessed = null;
class Signal {
constructor(initialValue) {
this._value = initialValue;
this._dependents = [];
}
get value() {
if (currentAccessed) {
this._addDependent(currentAccessed);
}
return this._value;
}
set value(newValue) {
if (this._value !== newValue) {
this._value = newValue;
this._notifyDependents();
}
}
_addDependent(dependent) {
if (!this._dependents.includes(dependent)) {
this._dependents.push(dependent);
}
}
_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) {
currentAccessed = this;
this._recomputeValue();
currentAccessed = null;
}
return this._value;
}
_recomputeValue() {
this._value = this._computeFn();
this._isStale = false;
}
_update() {
this._isStale = true;
}
}
class Effect {
constructor(effectFn) {
this._effectFn = effectFn;
this._isStale = true;
this._execute();
}
_execute() {
if (this._isStale) {
currentAccessed = this;
this._effectFn();
currentAccessed = null;
}
}
_update() {
this._isStale = true;
this._execute();
}
}
function createSignal(initialValue) {
return new Signal(initialValue);
}
function createComputed(computeFn) {
return new Computed(computeFn);
}
function createEffect(effectFn) {
return new Effect(effectFn);
}
// Creating signals
const count = createSignal(0);
const multiplier = createSignal(2);
// Creating an effect
createEffect(() => {
console.log("Effect called: Count is", count.value, "and multiplier is", multiplier.value);
});
// Changing signal values
count.value = 1;
multiplier.value = 3;