nostr:nprofile1qyt8wumn8ghj7mn0wd68yetvd96x2uewdaexwtcpz9mhxue69uhkummnw3ezuamfdejj7qgkwaehxw309ash2arg9ehx7um5wgcjucm0d5hszythwden5te0xy6rqtnxxaazu6t09uq3gamnwvaz7tmpd3nk7tn4w3ux7tn0dejj7qpqwqfzz2p880wq0tumuae9lfwyhs8uz35xd0kr34zrvrwyh3kvrzus7hy830 nostr:nprofile1qyfhwumn8ghj7ur4wfcxcetsv9njuetn9uq32amnwvaz7tmjv4kxz7fwv3sk6atn9e5k7tcpzamhxue69uhhyetvv9ujumn0wd68ytnzv9hxgtcpr9mhxue69uhhyetvv9ujuumwdae8gtnnda3kjctv9uq3vamnwvaz7tm9v3jkutnwdaehgu3wd3skuep0qqsdgawwfvuhw5r3xr6zcluxx3h0jd5qpuawwn27e7qgj2qvmsvj86gqdgymm

Reply to this note

Please Login to reply.

Discussion

Taking a look at this...it's a really odd pattern, but it also doesn't surprise me that it's not working.

The `value` prop is: a) only scoped to `Component1`, and b) never passed to `Component2`. Since the `state` object on `+page.svelte` is redeclared, `value` doesn't live there, either. It looks to me like Svelte is doing the natural thing and letting `value` be destroyed with its owner (i.e., `Component1`).

Interestingly, the `closure` function seems to outlive its component. As your example solution suggests, copying `value` into the closure's scope ensures `value` has the same lifespan as `closure`.

How come this worked in Svelte 4? I'm trying to understand what Svelte/JS is doing with the references under the hood that would explain the behavior.

The pattern is really weird in isolation, but it makes sense for use cases like portals and modal dialogs.

It worked in svelte 4 because this is just how javascript works. It seems like svelte 5 is trying to re-implement garbage collection by undefining props on unmount. Svelte 4 just used javascript for state management — even though there was some compiler magic with stores that get `unsubscribe` called automatically, it was basically relying on the javascript VM's garbage collector to avoid memory leaks. I suspect something about runes makes this more difficult.

Maybe the most idiomatic way to implement this pattern with modals in Svelte 5 is to use snapshots. That may suffice to capture the variables the closure needs into a persisted context.

https://svelte.dev/docs/kit/snapshots

In fact it doesn't, you have to re-assign the variable in order to break reactivity

Dang.

Interestingly, I did try putting a `const newValue = value` inside the callback body in your example, and even that didn't work.

It seems like the Svelte compiler should undefine functions in component bodies, to be thorough, since those functions lose their captured context. Then everything in a component would be tied to its lifecycle, not just some things.

Maybe doing that with functions has other problems, though.

The problem is that svelte is trying to re-invent garbage collection. It seems to me like you could just... let stuff be defined, and it would disappear when everything that holds a reference to it gets collected.