makeObservable (from MobX) to solidjs (not sure if this is a good idea)
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
import { createSignal, createComputed } from "solid-js"; | |
function createProperty<T, O>(o: O, n: keyof O, def: T) { | |
const [get, set] = createSignal(def); | |
Object.defineProperty(o, n, { | |
get, | |
set, | |
}); | |
return def; | |
} | |
export function makeObservable(o: any) { | |
Object.getOwnPropertyNames(o).forEach((name) => { | |
createProperty(o, name, o[name]); | |
}); | |
} | |
// Use case | |
class ImageZoomerState { | |
zoom: number; | |
pan: { x: number; y: number }; | |
constructor() { | |
this.zoom = 0; | |
this.pan = { x: 0, y: 0 }; | |
makeObservable(this); | |
} | |
} | |
let s = new ImageZoomerState(); | |
createComputed(() => { | |
console.log("new pan!", s.pan.x, s.pan.y); | |
}); | |
createComputed(() => { | |
console.log("new zoom!", s.zoom); | |
}); | |
s.zoom = 0.5; | |
s.pan = { x: 1, y: 2 }; | |
// Note: This does not trigger observable | |
// s.pan.x = 5; | |
setTimeout(() =>{ | |
s.pan = { x: 1, y: 3 }; | |
}, 1000); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment