Last active
March 14, 2023 18:15
-
-
Save segefjord/625ef854a899653d5acf652b813f784f to your computer and use it in GitHub Desktop.
Reactive browser console
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
const setWm = (wm, obj, v) => { | |
wm.set(obj, Object.assign(wm.get(obj), { internal: v })) | |
wm.get(obj).listener(v) | |
} | |
const bindWm = (wm, obj, ref, f) => { | |
wm.set(obj, { | |
listener: () => {}, | |
listen: function(listener) { this.listener = listener }, | |
internal: ref, | |
}) | |
wm.get(obj).listen(f) | |
} | |
const bindConsole = (obj, str, ref, f) => { | |
const wm = new WeakMap() | |
const pattern = { | |
get() { return wm.get(this).internal }, | |
set(v) { setWm(wm, this, v) } | |
} | |
bindWm(wm, obj, ref, f) | |
Object.defineProperty(obj, str, pattern) | |
} | |
export default bindConsole |
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> | |
// this is actually a svelte component | |
// .html is just for syntax highlight | |
import bindConsole from './bindConsole' | |
let myProp = 10 // svelte state | |
window.app = {} // assign global variable app | |
window.app.myProp = myProp // assign myProp (not reactive yet) | |
// tada! | |
bindConsole(window.app, 'myProp', myProp, (newVal) => { myProp = newVal }) | |
// global app.myProp is now reactive with internal svelte variable myProp | |
</script> | |
<h1> myProp: {myProp} </h1> |
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
https://svelte.dev/repl/e139ee91c1834124a2dcf891c2049b83?version=3.52.0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment