Created
April 16, 2022 12:52
-
-
Save foolishway/3e05f65438b15016c79d73902cf12844 to your computer and use it in GitHub Desktop.
This file contains 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
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