Skip to content

Instantly share code, notes, and snippets.

@ilya-korotya
Created August 1, 2018 07:18
Show Gist options
  • Save ilya-korotya/74ea761222825c930293d7f2dfaccc71 to your computer and use it in GitHub Desktop.
Save ilya-korotya/74ea761222825c930293d7f2dfaccc71 to your computer and use it in GitHub Desktop.
Reactive with vanilla JS
let data = { price: 5, quantity: 2 }
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())
}
}
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(() => {
data.total = data.price * data.quantity
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment