1

I'm trying to create new instances of the same component in svelte whenever a button or other action happens on the page, without having to make a list and {each} over them. I just want to do something like new Component(some context data) and forget. Another concern is I don't want the component to disappear when the parent is removed.

Thank you

1 Answer 1

2

Just mount it straight on the document.body:

new Component({ target: document.body })

But be aware that if you do not $destroy it yourself, you will end up with a memory leak.

When I do something like this, e.g. for notifications, I dispatch an event from the component that tells the calling code when the component can safely be destroyed. Something like:

const notification = new Notification({ target: document.body, ... });
notification.$on('close', () => notification.$destroy());
Sign up to request clarification or add additional context in comments.

5 Comments

This seems to be exactly what I need, I'm just wondering what happens when say the caller (parent) no longer exists when the event is fired, does it still destroy / clean up ? Edit: my guess is yes, since the event is set to the notif itself right?
@LAZ: This will work without issue (REPL example).
Oh, last thing, now that I've made a helper func to handle this behavior, I'm having trouble passing elements for the slots in the components. I know how to pass props, but nothing else really
Slots in the client-side API are currently not supported, there is a Github issues about that somewhere. I would probably just bind an element within the instantiated component and append to that instead. To access props directly, the component needs to be compiled with <svelte:options accessors />. (REPL example)
Ok thank you. I passed components as props and used <svelte:component> to instantiate them, works well enough for my needs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.