8000 Pass events to dynamic components · Issue #5265 · sveltejs/svelte · GitHub
[go: up one dir, main page]

Skip to content

Pass events to dynamic components #5265

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
rottmann opened this issue Aug 13, 2020 · 4 comments
Closed

Pass events to dynamic components #5265

rottmann opened this issue Aug 13, 2020 · 4 comments

Comments

@rottmann
Copy link

Is it possible to pass events to dynamic components?
E.g. pass on:click as props and recieve the click event.

Made a full exmaple: https://svelte.dev/repl/a16dd36f0265408a9c42409986b44acd?version=3.24.1

Short Version:

Example.svelte

<script>
  export let component
  export let props
</script>

<svelte:component
  this={component}
  {...props}
></svelte:component>

Example call

<script>
import Example from './Example.svelte'
const component = ... // some svelte component e.g. a Button
const props = {
  'on:click' = (e) => console.log('THIS SHOULD BE CALLED')
}
</script>

<Example {component} {props}></Example>

The on:click will not be triggered, only if i wrote it like this

<Example {component} {props} on:click={(e) => props['on:click'](e)}></Example>

But in this case i have to call the click targets manually.

@Conduitry
Copy link
Member

Directives (like on:foo={bar}) aren't the same as props. Spreads on components only set props. If you need to be able to customize this at runtime, you can write the child component to accept props which are callbacks instead of having it dispatch events.

@rottmann
Copy link
Author

Thats what i currently do, write callbacks and dispatchers, very uncomfortable. I dont know which directives the passed components have.

The question is then how can i pass directives dynamically to components? Or why it is not possible to pass them this way?

Svelte creates bindings when you write it like this

<MyComponent on:click={doSomething}></MyComponent>

It would be nice if we can have access to set the bindings via a function, e.g.

<script>
  let myComponent

  myComponent.addListener('click', doSomething)
</script>

<MyComponent bind:this={myComponent]></MyComponent>

Internally svelte does the same.

@Rich-Harris
Copy link
Member

Closing as spreading events is supported in Svelte 5

@Rich-Harris Rich-Harris reopened this Apr 2, 2024
@Rich-Harris
Copy link
Member

errr, oops... this was already closed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants
0