Svelte 5 runes encapsulation
I've been tooling around with svelte 5's runes and I'm wondering if it is possible with the current design to encapsulate mutation to state with runes. Is it possible to have a uni-directional data flow and thereby create MVC / MVVM type patterns with runes, or is this the wrong approach?
I'll provide an example to clarify my question:
export const count = () => {
const countsState = $state<CountObj[]>([
{ name: 'foo', count: 0 },
{ name: 'bar', count: 0 },
{ name: 'baz', count: 0 }
]);
return {
get state() {
return countsState;
},
addCount: (name: string) => {
state.push({ name, count: 0 });
},
incrCount(name: string) {
const count = state.find((c) => c.name == name);
if (count) count.count++;
}
};
};
With this example I am still able to mutate the inner state of state from outside of this structure.
counts.state[0].count++;
I want to restrict access to count's state and only allow mutations to happen from within the controller of the state. Is there a pattern for this yet?
It seems like if we are directly exposing the mutable state to the world that that type of pattern/encapsulation wouldn't really exist.
Posted Mar 2, 2024, 4:04 PM UTC