javascript / beginner
Snippet
Managing Component State with OOP Classes
Object-oriented programming (OOP) principles can be used to encapsulate state and business logic inside JavaScript classes. Svelte components can instantiate these service objects and bridge class state updates to reactive variables via callbacks.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<script>class Stopwatch {constructor() {this.seconds = 0;this.timerId = null;}start(callback) {if (this.timerId) return;this.timerId = setInterval(() => {this.seconds += 1;callback(this.seconds);}, 1000);}stop() {clearInterval(this.timerId);this.timerId = null;}}const stopwatch = new Stopwatch();let elapsed = 0;</script><p>Elapsed time: {elapsed}s</p><button on:click={() => stopwatch.start(val => elapsed = val)}>Start</button><button on:click={() => stopwatch.stop()}>Stop</button>
svelte
Breakdown
1
class Stopwatch {
Defines an ES6 class encapsulating the internal timer properties and behavior.
2
const stopwatch = new Stopwatch();
Instantiates the class object to manage stopwatch logic independently from component rendering.