mirror of https://github.com/sveltejs/svelte
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
57 lines
1.9 KiB
57 lines
1.9 KiB
6 years ago
|
---
|
||
|
title: Auto-subscriptions
|
||
|
---
|
||
|
|
||
2 years ago
|
The app in the previous example works, but there's a subtle bug — the store is subscribed to, but never unsubscribed. If the component was instantiated and destroyed many times, this would result in a _memory leak_.
|
||
6 years ago
|
|
||
4 years ago
|
Start by declaring `unsubscribe` in `App.svelte`:
|
||
|
|
||
|
```js
|
||
2 years ago
|
const unsubscribe = count.subscribe((value) => {
|
||
3 years ago
|
countValue = value;
|
||
4 years ago
|
});
|
||
|
```
|
||
2 years ago
|
|
||
3 years ago
|
> Calling a `subscribe` method returns an `unsubscribe` function.
|
||
4 years ago
|
|
||
3 years ago
|
You now declared `unsubscribe`, but it still needs to be called, for example through the `onDestroy` [lifecycle hook](/tutorial/ondestroy):
|
||
6 years ago
|
|
||
2 years ago
|
```svelte
|
||
6 years ago
|
<script>
|
||
|
import { onDestroy } from 'svelte';
|
||
|
import { count } from './stores.js';
|
||
|
import Incrementer from './Incrementer.svelte';
|
||
|
import Decrementer from './Decrementer.svelte';
|
||
|
import Resetter from './Resetter.svelte';
|
||
|
|
||
3 years ago
|
let countValue;
|
||
6 years ago
|
|
||
2 years ago
|
const unsubscribe = count.subscribe((value) => {
|
||
3 years ago
|
countValue = value;
|
||
6 years ago
|
});
|
||
|
|
||
|
onDestroy(unsubscribe);
|
||
|
</script>
|
||
|
|
||
3 years ago
|
<h1>The count is {countValue}</h1>
|
||
6 years ago
|
```
|
||
|
|
||
|
It starts to get a bit boilerplatey though, especially if your component subscribes to multiple stores. Instead, Svelte has a trick up its sleeve — you can reference a store value by prefixing the store name with `$`:
|
||
|
|
||
2 years ago
|
```svelte
|
||
6 years ago
|
<script>
|
||
|
import { count } from './stores.js';
|
||
|
import Incrementer from './Incrementer.svelte';
|
||
|
import Decrementer from './Decrementer.svelte';
|
||
|
import Resetter from './Resetter.svelte';
|
||
|
</script>
|
||
|
|
||
|
<h1>The count is {$count}</h1>
|
||
|
```
|
||
|
|
||
6 years ago
|
> Auto-subscription only works with store variables that are declared (or imported) at the top-level scope of a component.
|
||
|
|
||
6 years ago
|
You're not limited to using `$count` inside the markup, either — you can use it anywhere in the `<script>` as well, such as in event handlers or reactive declarations.
|
||
|
|
||
4 years ago
|
> Any name beginning with `$` is assumed to refer to a store value. It's effectively a reserved character — Svelte will prevent you from declaring your own variables with a `$` prefix.
|