Skip to content

Instantly share code, notes, and snippets.

@foolishway
Created April 16, 2022 12:52
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 foolishway/3e05f65438b15016c79d73902cf12844 to your computer and use it in GitHub Desktop.
Save foolishway/3e05f65438b15016c79d73902cf12844 to your computer and use it in GitHub Desktop.
class Wrapper {
constructor(value) {
this.value = value
this.dep = new Set()
}
addDep() {
if (activeUpdate) {
this.dep.add(activeUpdate)
}
}
fireDep() {
this.dep.forEach(dep => {
if (typeof dep === 'function') {
dep()
}
})
}
}
const log = console.log
function refs(value) {
let wrapped = new Wrapper(value)
let proxyObj = new Proxy(wrapped, {
get(obj, prop) {
obj.addDep()
return obj[prop]
},
set(obj, prop, val) {
obj[prop] = val;
obj.fireDep();
}
})
return proxyObj;
}
let activeUpdate = null;
function autorun(fn) {
let wrappedUpdate = () => {
activeUpdate = wrappedUpdate
fn()
activeUpdate = null;
}
wrappedUpdate()
}
let reactiveCount = refs(0)
autorun(() => log(reactiveCount.value))
reactiveCount.value = 1
reactiveCount.value = 2
reactiveCount.value = 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment