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 }
class Dep { constructor () { this.subscribers = [] } depend () { if (target && !this.subscribers.includes(target)) { this.subscribers.push(target) } } notify () { this.subscribers.forEach(sub => sub()) } }
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)
|