-
Notifications
You must be signed in to change notification settings - Fork 0
/
Watcher.js
54 lines (48 loc) · 935 Bytes
/
Watcher.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
/*
Dep, 用于进行监视器的添加和执行
*/
class Dep {
constructor(){
this.watchers = []
}
addWatcher(newWatch){
this.watchers.push(newWatch)
}
notify(){
this.watchers.forEach(e => {
e.update()
})
}
}
/*
监视器操作
*/
class Watcher{
constructor(vm, exp, cb){
this.vm = vm
this.cb = cb
this.exp = exp //a.b.c
//new Watcher()执行时,就对Dep.target进行赋值,便于添加到Dep中
Dep.target = this
this.value = this.get()
Dep.target = null
}
get(){
var value = this.vm
this.exp.split('.').forEach(key => {
value = value[key]
})
return value
}
update(){
var oldValue = this.value
var newValue = this.get();
if (oldValue != newValue){
this.value = newValue
//值变化之后,执行注册的回调函数
this.cb.call(this, this.value, oldValue)
} else {
return
}
}
}