javascript / beginner
Snippet
Encapsulating Component Business Logic in ES6 Classes within Svelte
Object-oriented design patterns allow grouping data and mutating behavior inside reusable ES6 classes. In Svelte, reassigning the class instance variable triggers top-level reactivity when internal instance properties change.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<script>class CounterModel {constructor(initial = 0) {this.count = initial;}increment() {this.count += 1;}}let model = new CounterModel(5);function handleStep() {model.increment();model = model;}</script><button on:click={handleStep}>Count: {model.count}</button>
svelte
Breakdown
1
class CounterModel {
Defines an object-oriented class structure to encapsulate counter state and operations.
2
let model = new CounterModel(5);
Instantiates a new counter object with an initial baseline value of 5.
3
model.increment();
Invokes the instance method to mutate the internal count property.
4
model = model;
Reassigns the reference to inform Svelte's reactivity system of property modifications.