Public
Edited
Oct 25, 2021
1 fork
Insert cell
# Reactivity with `Object.defineProperty`
Insert cell
{
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
}
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more