-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmy-ref.js
45 lines (45 loc) · 934 Bytes
/
my-ref.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
"use strict";
let activeEffect;
class ReactiveEffect {
constructor(fn) {
this.fn = fn;
}
run() {
activeEffect = this;
return this.fn();
}
}
function ref(value) {
return new RefImpl(value);
}
class RefImpl {
constructor(value) {
this.dep = new Set();
this._value = value;
}
get value() {
trackEffects(this.dep);
return this._value;
}
set value(newVal) {
this._value = newVal;
triggerEffects(this.dep);
}
}
function trackEffects(dep) {
if (activeEffect)
dep.add(activeEffect);
}
function triggerEffects(dep) {
for (const effect of dep) {
effect.run();
}
}
function myWatchEffect(fn) {
const effect = new ReactiveEffect(fn);
effect.run();
activeEffect = undefined;
}
const msg = ref("hello!");
myWatchEffect(() => console.log("I am tracking ", msg.value));
msg.value = "changed!";