javascript / expert
Snippet
Domain Logic Separation with Class-based Runes
In Svelte 5, classes can encapsulate reactive state using runes. This allows you to pull business logic out of components and into testable domain models. Unlike functional state, classes provide a clear structure for complex data and methods that automatically trigger UI updates when properties change.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class UserProfile {name = $state('');status = $state('offline');lastSeen = $derived(new Date().toLocaleTimeString());constructor(initialName) {this.name = initialName;}goOnline() {this.status = 'online';}}const user = new UserProfile('Markus');
svelte
Breakdown
1
name = $state('');
Defines a reactive property within the class instance.
2
lastSeen = $derived(...);
Creates a computed property that updates automatically based on dependencies.
3
this.status = 'online';
Mutating the class property triggers reactivity in all observing components.