dependency and autorun
by harps116
JavaScript
// Dependency tracking class.
class Dep {
constructor () {
this.subscribers = new Set()
}
// the current code depends on this
depend () {
if (activeUpdate) {
console.log(activeUpdate);
this.subscribers.add(activeUpdate)
}
}
// this dependency has changed and other vales that depend on this value need to be notified.
notify () {
this.subscribers.forEach(sub => sub())
}
}
let activeUpdate = null
// this is the reactive zone
function autorun (update) {
const wrappedUpdate = () => {
// this is the flag tell our class to add dependencies
activeUpdate = wrappedUpdate
update()
activeUpdate = null
}
wrappedUpdate()
}
const dep = new Dep()
autorun(() => {
dep.depend()
// registering dependenices
console.log('an update')
console.log('another side effect');
})
dep.notify()
// should log out the dependencies