Skip to content

Instantly share code, notes, and snippets.

@nemzyx
Last active March 14, 2023 18:15
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 nemzyx/625ef854a899653d5acf652b813f784f to your computer and use it in GitHub Desktop.
Save nemzyx/625ef854a899653d5acf652b813f784f to your computer and use it in GitHub Desktop.
Reactive browser console
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
<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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment