Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FocusThen/3df76b0eaa86d1e920bfbdaac1c75378 to your computer and use it in GitHub Desktop.
Save FocusThen/3df76b0eaa86d1e920bfbdaac1c75378 to your computer and use it in GitHub Desktop.
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