pull/10240/head
Rich Harris 3 years ago
parent e3ff46e0de
commit 87bf5ca823

@ -61,21 +61,21 @@ declare function $derived<T>(expression: T): T;
declare namespace $derived {
/**
* Sometimes you need to create complex derivations which don't fit inside a short expression.
* In this case, you can resort to `$derived.call` which accepts a function as its argument and returns its value.
* Sometimes you need to create complex derivations that don't fit inside a short expression.
* In these cases, you can use `$derived.call` which accepts a function as its argument.
*
* Example:
* ```ts
* $derived.call(() => {
* let tmp = count;
* if (count > 10) {
* tmp += 100;
* }
* return tmp * 2;
* let total = $derived.call(() => {
* let result = 0;
* for (const n of numbers) {
* result += n;
* }
* return result;
* });
* ```
*
* https://svelte-5-preview.vercel.app/docs/runes#$derived-fn
* https://svelte-5-preview.vercel.app/docs/runes#$derived-call
*/
export function fn<T>(fn: () => T): void;
}

@ -134,27 +134,29 @@ If the value of a reactive variable is being computed it should be replaced with
```
...`double` will be calculated first despite the source order. In runes mode, `triple` cannot reference `double` before it has been declared.
### `$derived.call`
## `$derived.call`
Sometimes you need to create complex derivations which don't fit inside a short expression. In this case, you can resort to `$derived.call` which accepts a function as its argument and returns its value.
Sometimes you need to create complex derivations that don't fit inside a short expression. In these cases, you can use `$derived.call` which accepts a function as its argument.
```svelte
<script>
let count = $state(0);
let complex = $derived.call(() => {
let tmp = count;
if (count > 10) {
tmp += 100;
let numbers = $state([1, 2, 3]);
let total = $derived.call(() => {
let total = 0;
for (const n of numbers) {
total += n;
}
return tmp * 2;
return total;
});
</script>
<button on:click={() => count++}>
{complex}
<button on:click={() => numbers.push(numbers.length + 1)}>
{numbers.join(' + ')} = {total}
</button>
```
In essence, `$derived(expression)` is equivalent to `$derived.call(() => expression)`.
## `$effect`
To run side-effects like logging or analytics whenever some specific values change, or when a component is mounted to the DOM, we can use the `$effect` rune:

Loading…
Cancel
Save