-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnextTick.js
65 lines (58 loc) · 1.04 KB
/
nextTick.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
let active
let watch = cb => {
active = cb
active()
active = null
}
// 核心:利用宏任务、微任务队列;
// 宏任务执行时添加微任务队列,后依次执行promise微任务
let queue = []
let nextTick = cb => Promise.resolve().then(cb)
let queueJob = job => {
if (!queue.includes(job)) {
queue.push(job)
nextTick(flushJobs)
}
}
let flushJobs = () => {
let job
while ((job = queue.shift()) !== undefined) {
job()
}
}
class Dep {
constructor() {
this.deps = new Set()
}
depend() {
if (active) {
this.deps.add(active)
}
}
notify() {
this.deps.forEach(dep => queueJob(dep))
}
}
let ref = initValue => {
let value = initValue
let dep = new Dep()
return Object.defineProperty({}, 'value', {
get() {
dep.depend()
return value
},
set(newValue) {
value = newValue
dep.notify()
}
})
}
let x = ref(1)
let y = ref(2)
let z = ref(2)
watch(() => {
console.log(`hello ${x.value} ${y.value} ${z.value} `)
})
x.value = 2
y.value = 3
z.value = 3