-
-
Save FocusThen/3df76b0eaa86d1e920bfbdaac1c75378 to your computer and use it in GitHub Desktop.
Vue.js-like Reactive Dependency
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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