As long as an object correctly implements the subscribe
method, it's a store. Beyond that, anything goes. It's very easy, therefore, to create custom stores with domain-specific logic.
For example, the count
store from our earlier example could include increment
, decrement
and reset
methods and avoid exposing set
and update
:
function createCount() {
const { subscribe, set, update } = writable(0);
return {
subscribe,
increment: () => update(n => n + 1),
decrement: () => update(n => n - 1),
reset: () => set(0)
};
}
App.svelte
stores.js
xxxxxxxxxx
9
1
<script>
2
import { count } from './stores.js';
3
</script>
4
5
<h1>The count is {$count}</h1>
6
7
<button on:click={count.increment}>+</button>
8
<button on:click={count.decrement}>-</button>
9
<button on:click={count.reset}>reset</button>
Console
xxxxxxxxxx
102
1
/* App.svelte generated by Svelte v3.23.2 */
2
import {
3
SvelteComponent,
4
append,
5
component_subscribe,
6
detach,
7
element,
8
init,
9
insert,
10
listen,
11
noop,
12
run_all,
13
safe_not_equal,
14
set_data,
15
space,
16
text
Compiler options
result = svelte.compile(source, {
generate:
});xxxxxxxxxx
1
1
/* Add a <style> tag to see compiled CSS */