-
Notifications
You must be signed in to change notification settings - Fork 154
/
《响应式系统的依赖收集追踪原理》.js
71 lines (60 loc) · 1.28 KB
/
《响应式系统的依赖收集追踪原理》.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
class Dep {
constructor () {
this.subs = [];
}
addSub (sub) {
this.subs.push(sub);
}
notify () {
this.subs.forEach((sub) => {
sub.update();
})
}
}
class Watcher {
constructor () {
Dep.target = this;
}
update () {
console.log("视图更新啦~");
}
}
function observer (value) {
if (!value || (typeof value !== 'object')) {
return;
}
Object.keys(value).forEach((key) => {
defineReactive(value, key, value[key]);
});
}
function defineReactive (obj, key, val) {
const dep = new Dep();
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
get: function reactiveGetter () {
dep.addSub(Dep.target);
return val;
},
set: function reactiveSetter (newVal) {
if (newVal === val) return;
val = newVal;
dep.notify();
}
});
}
class Vue {
constructor(options) {
this._data = options.data;
observer(this._data);
new Watcher();
console.log('render~', this._data.test);
}
}
let o = new Vue({
data: {
test: "I am test."
}
});
o._data.test = "hello,test.";
Dep.target = null;