-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathObserve.js
45 lines (41 loc) · 822 Bytes
/
Observe.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
/**
* 监听者,将data中数据绑定defineProperty
* [Observer description]
*/
let Observer = function (data) {
this.data = data;
this.init();
}
Observer.prototype.init = function () {
Object.keys(this.data).forEach(key => {
this.defineReactive(key, this.data[key]);
})
}
Observer.prototype.defineReactive = function (key, value) {
let self = this;
Observer.install(value);
let dep = new Dep();
Object.defineProperty(this.data, key, {
configurable: true,
enumerable: true,
get () {
if (Dep.target) {
dep.addSub(Dep.target)
}
return value;
},
set (newVal) {
if (newVal === value) {
return;
}
value = newVal;
dep.notify();
}
})
}
Observer.install = function (data) {
if (!data || typeof data !== 'object') {
return;
}
return new Observer(...arguments);
}