-
Notifications
You must be signed in to change notification settings - Fork 0
/
reactive.html
92 lines (78 loc) · 1.67 KB
/
reactive.html
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
<script>
class Dep {
constructor() {
this.subscribers = new Set();
}
depend() {
if (activeEffect) {
this.subscribers.add(activeEffect);
}
}
notify() {
this.subscribers.forEach(effect => {
effect();
})
}
}
function watchEffect(effect) {
activeEffect = effect
effect();
activeEffect = null;
}
const targetMap = new WeakMap()
const getDep = function(target, key) {
let depsMap = targetMap.get(target);
if (!depsMap) {
depsMap = new Map();
targetMap.set(target, depsMap);
}
let dep = depsMap.get(key);
if (!dep) {
dep = new Dep();
depsMap.set(key, dep);
}
return dep;
}
const reactivehandler = {
get(target, key, receiver) {
const dep = getDep(target, key);
dep.depend();
return target[key];
},
set(target, key, value) {
const dep = getDep(target, key);
target[key] = value;
dep.notify();
return true;
}
}
// Vue3
function reactive(raw) {
return new Proxy(raw, reactivehandler);
}
// Vue2
// function reactive(raw) {
// Object.keys(raw).forEach((key) => {
// const dep = new Dep();
// let value = raw[key];
// Object.defineProperty(raw, key, {
// get() {
// dep.depend();
// return value;
// },
// set(newValue) {
// value = newValue;
// dep.notify();
// }
// })
// })
// return raw;
// }
const state = reactive({
count: 0
});
watchEffect(() => {
console.log(state.count);
})
state.count += 1;
</script>