0 day streak
javascript / intermediate
Snippet

Encapsulating Logic with Custom Stores

A custom store is any object that implements a 'subscribe' method. By wrapping a standard writable store and exposing only specific methods, you can encapsulate domain logic and prevent external code from directly setting arbitrary values.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
import { writable } from 'svelte/store';
function createCounter() {
const { subscribe, update } = writable(0);
return {
subscribe,
increment: () => update(n => n + 1),
reset: () => update(() => 0)
};
}
export const count = createCounter();
svelte
Breakdown
1
return { subscribe, ... }
By returning 'subscribe', the object adheres to the Svelte store contract.
2
increment: () => update(...)
Exposes a controlled way to modify the state without giving full access to 'set'.