Skip to content

Instantly share code, notes, and snippets.

@saveroo
Last active September 18, 2019 10:37
Show Gist options
  • Save saveroo/d6f522d3f2803ad0290f82bbaf6298c7 to your computer and use it in GitHub Desktop.
Save saveroo/d6f522d3f2803ad0290f82bbaf6298c7 to your computer and use it in GitHub Desktop.
Reactivity Observer
let data = {price: 5, quantity: 2}
let total, salePrice, discountedTotal
let target = null
class Dep {
constructor() {
this.subscriber = []
}
depend() {
if(target && !this.subscriber.includes(target)) {
this.subscriber.push(target)
}
}
notify() {
this.subscriber.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(newVal) {
internalValue = newVal
dep.notify()
}
})
})
function watcher(myFunc) {
target = myFunc
target()
target = null
}
watcher(() => {
total = data.price * data.quantity
})
watcher(() => {
salePrice = data.price * 0.9
})
watcher(() => {
discountedTotal = data.price * 0.9 * data.quantity
})
data.price = 1;
console.log(total) // 2
data.price = 20;
data.quantity = 10;
console.log(total) // 200
console.log(discountedTotal) // 180
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment