-
Notifications
You must be signed in to change notification settings - Fork 0
/
my-ref.ts
56 lines (44 loc) · 985 Bytes
/
my-ref.ts
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
type Dep = Set<ReactiveEffect>;
let activeEffect: ReactiveEffect | undefined;
class ReactiveEffect<T = any> {
constructor(public fn: () => T) {
}
run() {
activeEffect = this;
return this.fn();
}
}
function ref<T>(value: T) {
return new RefImpl(value);
}
class RefImpl<T> {
private _value: T;
public dep: Dep = new Set();
constructor(value: T) {
this._value = value;
}
get value() {
trackEffects(this.dep);
return this._value;
}
set value(newVal) {
this._value = newVal;
triggerEffects(this.dep);
}
}
function trackEffects(dep: Dep) {
if (activeEffect) dep.add(activeEffect);
}
function triggerEffects(dep: Dep) {
for (const effect of dep) {
effect.run();
}
}
function myWatchEffect(fn:()=>any):void {
const effect = new ReactiveEffect(fn)
effect.run()
activeEffect = undefined;
}
const msg = ref<string>("hello!")
myWatchEffect(()=>console.log("I am tracking ",msg.value))
msg.value = "changed!"