-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathObserver.js
76 lines (72 loc) · 1.78 KB
/
Observer.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
72
73
74
75
76
class Watcher {
constructor(vm, expr, cb) {
this.vm = vm;
this.expr = expr;
this.cb = cb;
// 先把旧值保存起来
this.oldVal = this.getOldVal();
}
getOldVal() {
Dep.target = this;
const oldVal = compileUtil.getVal(this.expr, this.vm);
Dep.target = null;
return oldVal;
}
update() {
const newVal = compileUtil.getVal(this.expr, this.vm);
if(newVal !== this.oldVal) {
this.cb(newVal);
}
}
}
class Dep {
constructor() {
this.subs = [];
}
// 收集观察者
addSub(watcher) {
this.subs.push(watcher);
}
// 通知观察者去更新
notify() {
console.log("通知了观察者", this.subs);
this.subs.forEach(w => w.update())
}
}
class Observer{
constructor(data) {
this.observe(data);
}
observe(data) {
/**
*
*/
if(data && typeof data === "object") {
Object.keys(data).forEach(key => {
this.defineReactive(data, key, data[key]);
})
}
}
defineReactive(obj, key, value) {
// 递归遍历
this.observe(value);
const dep = new Dep();
Object.defineProperty(obj, key, {
enumerable: true,
configurable: false,
get() {
// 订阅数据变化时,往Dep中添加观察者
Dep.target && dep.addSub(Dep.target);
return value;
},
set: newVal => {
this.observe(newVal);
if(newVal !== value) {
value = newVal;
}
// 告诉Dep通知变化
ep.notify();
}
})
}
}