Skip to content

Commit 7239cbb

Browse files
committed
allow setup to return a teardown function
1 parent 92cb9f8 commit 7239cbb

File tree

4 files changed

+36
-3
lines changed

4 files changed

+36
-3
lines changed

packages/svelte/src/internal/client/dom/blocks/snippet.js

+6-2
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
/** @import { Getters } from '#shared' */
44
import { add_snippet_symbol } from '../../../shared/validate.js';
55
import { EFFECT_TRANSPARENT } from '../../constants.js';
6-
import { branch, block, destroy_effect } from '../../reactivity/effects.js';
6+
import { branch, block, destroy_effect, teardown } from '../../reactivity/effects.js';
77
import {
88
dev_current_component_function,
99
set_dev_current_component_function
@@ -92,8 +92,12 @@ export function createRawSnippet(fn) {
9292
anchor.before(element);
9393
}
9494

95-
snippet.setup?.(element);
95+
const result = snippet.setup?.(element);
9696
assign_nodes(element, element);
97+
98+
if (typeof result === 'function') {
99+
teardown(result);
100+
}
97101
}
98102
);
99103
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import { flushSync } from 'svelte';
2+
import { test } from '../../test';
3+
4+
export default test({
5+
test({ target, assert, logs }) {
6+
const button = target.querySelector('button');
7+
8+
flushSync(() => button?.click());
9+
assert.deepEqual(logs, ['tearing down']);
10+
}
11+
});
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
<script>
2+
import { createRawSnippet } from 'svelte';
3+
4+
let show = $state(true);
5+
6+
const snippet = createRawSnippet(() => ({
7+
render: () => `<hr>`,
8+
setup(p) {
9+
return () => console.log('tearing down')
10+
}
11+
}));
12+
</script>
13+
14+
<button onclick={() => show = !show}>click</button>
15+
16+
{#if show}
17+
{@render snippet()}
18+
{/if}

sites/svelte-5-preview/src/routes/docs/content/01-api/05-imports.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -122,7 +122,7 @@ The `setup` function is called during `mount` or `hydrate` with that same elemen
122122
{@render greet(name)}
123123
```
124124

125-
If the snippet is fully static, you can omit the `setup` function.
125+
If `setup` returns a function, it will be called when the snippet is unmounted. If the snippet is fully static, you can omit the `setup` function altogether.
126126

127127
## `svelte/reactivity`
128128

0 commit comments

Comments
 (0)