{
let target = null
class Dep {
constructor() {
this.subscribers = []
}
depend() {
if (target && !this.subscribers.includes(target)) {
this.subscribers.push(target)
}
}
notify() {
this.subscribers.forEach(sub => sub())
}
}
const data = {
price: 20,
amount: 5,
}
Object.keys(data).forEach(key => {
let internalValue = data[key]
const dep = new Dep()
Object.defineProperty(data, key, {
get() {
dep.depend()
return internalValue
},
set(newVal) {
internalValue = newVal
dep.notify()
},
})
})
function watcher(fn) {
target = fn
target()
target = null
}
watcher(() => {
data.total = data.price * data.amount
})
const ret = [data.total]
data.price = 30
ret.push(data.total)
return ret
}