javascript / expert
Snippet
Encapsulating State via Functional Runes
In Svelte 5, classes are no longer strictly necessary for complex state management. Factory functions returning objects with 'get' accessors allow for clean encapsulation while maintaining full reactivity. This pattern is superior for composition because it avoids 'this' binding issues and provides a clear, read-only interface for state properties, ensuring that state can only be mutated through defined methods like 'add' or 'toggle'.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
export function createLogger(prefix: string) {let logs = $state<string[]>([]);let isPaused = $state(false);return {get history() { return logs; },get status() { return isPaused ? 'Paused' : 'Active'; },add: (msg: string) => {if (!isPaused) logs.push(`[${prefix}] ${msg}`);},toggle: () => isPaused = !isPaused};}
svelte
Breakdown
1
let logs = $state<string[]>([]);
Initializes a reactive state inside the function closure.
2
get history() { return logs; }
Using a getter ensures that whoever consumes the object gets a reactive reference to the 'logs' array.
3
add: (msg: string) => { ... }
A closure-bound function that encapsulates the logic for mutating the private state.