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.
19 lines
849 B
19 lines
849 B
6 years ago
|
---
|
||
|
title: Readable stores
|
||
|
---
|
||
|
|
||
|
Not all stores should be writable by whoever has a reference to them. For example, you might have a store representing the mouse position or the user's geolocation, and it doesn't make sense to be able to set those values from 'outside'. For those cases, we have *readable* stores.
|
||
|
|
||
|
Click over to the `stores.js` tab. The first argument to `readable` is a `start` function that takes a `set` callback and returns a `stop` function. The `start` function is called when the store gets its first subscriber; `stop` is called when the last subscriber unsubscribes. The second (optional) argument is the initial value.
|
||
|
|
||
|
```js
|
||
|
export const time = readable(function start(set) {
|
||
|
const interval = setInterval(() => {
|
||
|
set(new Date());
|
||
|
}, 1000);
|
||
|
|
||
|
return function stop() {
|
||
|
clearInterval(interval);
|
||
|
};
|
||
|
}, new Date());
|
||
|
```
|