Skip to content

Instantly share code, notes, and snippets.

@Ciantic
Last active Sep 18, 2021
Embed
What would you like to do?
makeObservable (from MobX) to solidjs (not sure if this is a good idea)
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