|
2 | 2 | title: {@attach ...}
|
3 | 3 | ---
|
4 | 4 |
|
5 |
| -Attachments are functions that run when an element is mounted to the DOM. Optionally, they can return a function that is called when the element is later removed from the DOM. |
| 5 | +Attachments are functions that run in an [effect]($effect) when an element is mounted to the DOM or when [state]($state) read inside the function updates. |
| 6 | + |
| 7 | +Optionally, they can return a function that is called before the attachment re-runs, or after the element is later removed from the DOM. |
6 | 8 |
|
7 | 9 | > [!NOTE]
8000
div>
|
8 | 10 | > Attachments are available in Svelte 5.29 and newer.
|
@@ -55,7 +57,7 @@ A useful pattern is for a function, such as `tooltip` in this example, to _retur
|
55 | 57 | </button>
|
56 | 58 | ```
|
57 | 59 |
|
58 |
| -Since the `tooltip(content)` expression runs inside an [effect]($effect), the attachment will be destroyed and recreated whenever `content` changes. |
| 60 | +Since the `tooltip(content)` expression runs inside an [effect]($effect), the attachment will be destroyed and recreated whenever `content` changes. The same thing would happen for any state read _inside_ the attachment function when it first runs. (If this isn't what you want, see [Controlling when attachments re-run](#Controlling-when-attachments-re-run).) |
59 | 61 |
|
60 | 62 | ## Inline attachments
|
61 | 63 |
|
@@ -126,6 +128,35 @@ This allows you to create _wrapper components_ that augment elements ([demo](/pl
|
126 | 128 | </Button>
|
127 | 129 | ```
|
128 | 130 |
|
| 131 | +## Controlling when attachments re-run |
| 132 | + |
| 133 | +Attachments, unlike [actions](use), are fully reactive: `{@attach foo(bar)}` will re-run on changes to `foo` _or_ `bar` (or any state read inside `foo`): |
| 134 | + |
| 135 | +```js |
| 136 | +// @errors: 7006 2304 2552 |
| 137 | +function foo(bar) { |
| 138 | + return (node) => { |
| 139 | + veryExpensiveSetupWork(node); |
| 140 | + update(node, bar); |
| 141 | + }; |
| 142 | +} |
| 143 | +``` |
| 144 | + |
| 145 | +In the rare case that this is a problem (for example, if `foo` does expensive and unavoidable setup work) consider passing the data inside a function and reading it in a child effect: |
| 146 | + |
| 147 | +```js |
| 148 | +// @errors: 7006 2304 2552 |
| 149 | +function foo(+++getBar+++) { |
| 150 | + return (node) => { |
| 151 | + veryExpensiveSetupWork(node); |
| 152 | + |
| 153 | ++++ $effect(() => { |
| 154 | + update(node, getBar()); |
| 155 | + });+++ |
| 156 | + } |
| 157 | +} |
| 158 | +``` |
| 159 | + |
129 | 160 | ## Creating attachments programmatically
|
130 | 161 |
|
131 | 162 | To add attachments to an object that will be spread onto a component or element, use [`createAttachmentKey`](svelte-attachments#createAttachmentKey).
|
0 commit comments