-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathvue.js
68 lines (68 loc) · 1.12 KB
/
vue.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
let depId = 0
class Dep {
static target
id
subs
constructor(){
this.subs = []
this.id = depId++
Dep.target = null
}
addsub(sub){
this.subs.push(sub)
}
removesub(sub){
const index = this.subs.indexOf(sub)
if(index>-1){
this.subs.splice(index,1)
}
}
depend(){
if(Dep.target){
Dep.target.addDep(this)
}
}
notify(){
const subs = this.subs.slice()
subs.sort((a,b)=>a.id-b.id)
subs.forEach(item=>item.update())
}
}
class Watch{
constructor(data,key,callback){
Dep.target = this
this.value = data[key]
this.callback = callback
Dep.target = null
}
addDep(dep){
dep.addsub(this)
}
update(){
this.callback()
}
}
function defineReactive(data,key,val){
const dep = new Dep()
Object.defineProperty(data,key,{
configurable:true,
enumerable:true,
get(){
dep.depend()
return val
},
set(newValue){
if(newValue!=val){
val = newValue
dep.notify()
}
}
})
}
let data = {}
defineReactive(data,'a',1)
new Watch(data,'a',function(){
console.log(data.a)
})
data.a = 2
data.a = 4