5 ms·
I wrote a similar thing for svelte stores. The live example is here. https://svelte.dev/repl/4434d8fcd12242d79887343fd95e429c?version=3.29.7 https://svelte.dev
by injidup 5y ago
I wrote a similar thing for svelte stores. The live example is here.
https://svelte.dev/repl/4434d8fcd12242d79887343fd95e429c?version=3.29.7 https://svelte.dev/repl/4434d8fcd12242d79887343fd95e429c?ver...
You can wrap pretty much any POD/array data type as a store then index into it to generate new stores with view on to sub elements.
Note that a "store" is a reactive data store. You can set a value on it and also get notified of changes.
This means you can have a single store for your main data and then pass views on that data to sub components.
Views are created using selector expressions.
let data = {
name: 'thomas',
age: 25
}
let root = writable(data)
let rootUndo = undoStore(root)
let nameStore = subStore(rootUndo, v=>v.name)
let ageStore = subStore(rootUndo, v=>v.age)
let undoDisabled = derived(rootUndo.canUndo, u=>!u)
let redoDisabled = derived(rootUndo.canRedo, u=>!u)
----
<input type="text" bind:value={$nameStore}/>
<input type="number" bind:value={$ageStore}/>
<button on:click={undo} disabled= {$undoDisabled}>undo</button>
<button on:click={redo} disabled= {$redoDisabled}>redo</button>
Library is here https://github.com/bradphelan/immer.loves.svelte https://github.com/bradphelan/immer.loves.svelte
- hamilton 5y agolove this. I similarly use immer for just about every svelte project I build & maintain.
- injidup 5y agoWhen I built this I used immer under the hood. But actually I think it is not required. I'd have to have another look. I'm not really a front end dev but I just felt the whole "store" concept in svelte was incomplete and I could never understand the react/redux model. I had implemented something in .net years ago to simulate functional lenses and when I looked into immer I saw this JS proxy thing and realised I could easily build fully reactive lenses for svelte. In the end mostly an academic exercise as it is used in one internal office website and my day job is writing algorithms for CNC machines.