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
const data = {
price: 10,
quantity: 2
}

// 创建一个收集依赖项(依赖)并重新运行所有依赖项(通知)的Dep 类
class Dep {
constructor () {
this.subscribers = []
}
depend () {
if (target && !this.subscribers.includes(target)) {
this.subscribers.push(target)
}
}
notify () {
this.subscribers.forEach(sub => sub())
}
}

// 使用Object.defineProperty()创建 getter 和 setter
Object.keys(data).forEach( key => {
let internalValue = data[key]
const dep = new Dep()
Object.defineProperty( data, key, {
get () {
dep.depend()
return internalValue
},
set (newV) {
internalValue = newV
dep.notify()
}
})
})
// 创建一个观察者来管理我们正在运行的代码,这可能需要作为依赖项添加(目标)
function watcher(myFunc) {
target = myFunc
target()
target = null
}

watcher(() => {
data.total = data.price * data.quantity
})

data.price = 20

console.log(data.total)

最后更新: 2021年11月18日 13:38