Skip to content

Instantly share code, notes, and snippets.

@CodyJasonBennett
Last active January 22, 2023 01:32
Show Gist options
  • Save CodyJasonBennett/541b48d08ffb551730808496c5c29202 to your computer and use it in GitHub Desktop.
Save CodyJasonBennett/541b48d08ffb551730808496c5c29202 to your computer and use it in GitHub Desktop.
Proxy-wrap constructor side-effects
class CameraControls {
foo = { bar: true }
constructor(...args) {
console.log('impl construct', [...args])
}
dispose() {
console.log('impl disposed', this)
}
}
class CameraControlsImpl {
constructor(...args) {
const internal = {
_args: [...args],
_instance: null,
_props: {},
}
return new Proxy(this, {
set(target, key, value) {
if (key in internal) {
internal[key] = value
} else {
internal._props[key] = value
if (internal._instance) internal._instance[key] = value
}
return true
},
get(target, key) {
if (key in internal) return internal[key]
if (key in target) return target[key]
return internal._instance?.[key]
},
})
}
connect() {
this._instance = Object.assign(new CameraControls(...this._args), this._props)
}
disconnect() {
this._instance.dispose()
}
dispose() {
this.disconnect()
}
}
const controls = new CameraControlsImpl(1, 2, 3)
controls.test = true
controls.connect()
controls.test2 = false
console.log(controls.foo.bar)
controls.disconnect()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment