简单的 JavaScript Reactivity 实现

通过Object.defineProperty,简单地实现一个具备响应能力的Watcher方法。

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
const data = { price: 10, quantity: 2 };
let total = 0, target = null;
class Dep {
constructor() {
this.listeners = [];
}
depen() {
if (target && typeof target === 'function') {
this.listeners.push(target);
}
}
notify() {
this.listeners.forEach(listener => listener());
}
};
Object.keys(data).forEach(key => {
const dep = new Dep();
let originalValue = data[key];
Object.defineProperty(data, key, {
get() {
dep.depen();
return originalValue;
},
set(newVal) {
originalValue = newVal;
dep.notify();
},
});
});
function Watcher(func) {
target = func;
target();
target = null;
}
Watcher(() => {
total = data.price * data.quantity;
});
// total => 20
// data.price = 50
// total => 100
// data.quantity = 10
// total => 500