Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Vue.js-like Reactive Dependency
<script>
let activeEffect
class Dep {
// Initialize the value of the reactive dependency
constructor(value) {
this._value = value
this.subscribers = new Set()
}
// Getter of the dependency. Executed when a part of the software reads the value of it.
get value() {
this.depend()
return this._value
}
// Setter of the dependency. Executed when the value changes
set value(newValue) {
this._value = newValue
this.notify()
}
// Subscribe a new function as observer to the dependency
depend() {
if (activeEffect) this.subscribers.add(activeEffect)
}
// Notify subscribers of a value change
notify() {
this.subscribers.forEach((subscriber) => subscriber())
}
}
function watchEffect(fn) {
activeEffect = fn
fn()
activeEffect = null
}
// Trying out the dependency 👇 -------------------------
// Create a reactive dependency with the value of 1
const count = new Dep(1)
// Add a "watcher". This logs every change of the dependency to the console.
watchEffect(() => {
console.log('👻 value changed', count.value)
})
// Change value
setTimeout(() => {
count.value++
}, 1000)
setTimeout(() => {
count.value++
}, 2000)
setTimeout(() => {
count.value++
}, 3000)
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.