fix: ensure correct context for action update/destroy functions (#11023)

pull/11027/head
Rich Harris 6 months ago committed by GitHub
parent 34748ba015
commit ad11c5087f
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -0,0 +1,5 @@
---
'svelte': patch
---
fix: ensure correct context for action update/destroy functions

@ -11,9 +11,8 @@ import { deep_read_state, untrack } from '../../runtime.js';
export function action(dom, action, get_value) {
effect(() => {
var payload = untrack(() => action(dom, get_value?.()) || {});
var update = payload?.update;
if (get_value && update) {
if (get_value && payload?.update) {
var inited = false;
render_effect(() => {
@ -25,13 +24,15 @@ export function action(dom, action, get_value) {
deep_read_state(value);
if (inited) {
/** @type {Function} */ (update)(value);
/** @type {Function} */ (payload.update)(value);
}
});
inited = true;
}
return payload?.destroy;
if (payload?.destroy) {
return () => /** @type {Function} */ (payload.destroy)();
}
});
}

@ -0,0 +1,22 @@
import { ok, test } from '../../test';
import { flushSync, tick } from 'svelte';
import { log } from './log.js';
export default test({
html: `<button>0</button>`,
before_test() {
log.length = 0;
},
async test({ assert, target }) {
const btn = target.querySelector('button');
ok(btn);
flushSync(() => btn.click());
assert.deepEqual(log, ['update', 0, 1]);
flushSync(() => btn.click());
assert.deepEqual(log, ['update', 0, 1, 'destroy', 1]);
}
});

@ -0,0 +1,2 @@
/** @type {any[]} */
export const log = [];

@ -0,0 +1,28 @@
<script>
import { log } from './log.js';
let count = $state(0);
/**
* @param {Element} _
* @param {number} count
*/
function action(_, count) {
return {
count,
/** @param {number} count */
update(count) {
log.push('update', this.count, (this.count = count));
},
destroy() {
log.push('destroy', this.count);
},
}
};
</script>
{#if count < 2}
<button use:action={count} onclick={() => count++}>
{count}
</button>
{/if}
Loading…
Cancel
Save