Skip to content

Commit 9834c55

Browse files
committed
fix: ensure correct context for action update/destroy functions
1 parent 0a16292 commit 9834c55

File tree

5 files changed

+62
-4
lines changed

5 files changed

+62
-4
lines changed

.changeset/curvy-flies-exercise.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'svelte': patch
3+
---
4+
5+
fix: ensure correct context for action update/destroy functions

packages/svelte/src/internal/client/dom/elements/actions.js

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,8 @@ import { deep_read_state, untrack } from '../../runtime.js';
1111
export function action(dom, action, get_value) {
1212
effect(() => {
1313
var payload = untrack(() => action(dom, get_value?.()) || {});
14-
var update = payload?.update;
1514

16-
if (get_value && update) {
15+
if (get_value && payload?.update) {
1716
var inited = false;
1817

1918
render_effect(() => {
@@ -25,13 +24,15 @@ export function action(dom, action, get_value) {
2524
deep_read_state(value);
2625

2726
if (inited) {
28-
/** @type {Function} */ (update)(value);
27+
/** @type {Function} */ (payload.update)(value);
2928
}
3029
});
3130

3231
inited = true;
3332
}
3433

35-
return payload?.destroy;
34+
if (payload?.destroy) {
35+
return () => /** @type {Function} */ (payload.destroy)();
36+
}
3637
});
3738
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import { ok, test } from '../../test';
2+
import { flushSync, tick } from 'svelte';
3+
import { log } from './log.js';
4+
5+
export default test({
6+
html: `<button>0</button>`,
7+
8+
before_test() {
9+
log.length = 0;
10+
},
11+
12+
async test({ assert, target }) {
13+
const btn = target.querySelector('button');
14+
ok(btn);
15+
16+
flushSync(() => btn.click());
17+
assert.deepEqual(log, ['update', 0, 1]);
18+
19+
flushSync(() => btn.click());
20+
assert.deepEqual(log, ['update', 0, 1, 'destroy', 1]);
21+
}
22+
});
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
/** @type {any[]} */
2+
export const log = [];
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
<script>
2+
import { log } from './log.js';
3+
4+
let count = $state(0);
5+
6+
/**
7+
* @param {Element} _
8+
* @param {number} count
9+
*/
10+
function action(_, count) {
11+
return {
12+
count,
13+
/** @param {number} count */
14+
update(count) {
15+
log.push('update', this.count, (this.count = count));
16+
},
17+
destroy() {
18+
log.push('destroy', this.count);
19+
},
20+
}
21+
};
22+
</script>
23+
24+
{#if count < 2}
25+
<button use:action={count} onclick={() => count++}>
26+
{count}
27+
</button>
28+
{/if}

0 commit comments

Comments
 (0)