Raise/handle event from/of dynamic component

48 Views Asked by At

I'm currently facing the following problem.

I have a ComponentA which renders dynamic components of unknown type (ComponentA gets these components to render via its props - importin these component types is not conceivable, as there would be too many and it can grow dynamically over time.).

The dynamic component dispatches an event called "testEvent". I now want to react to this event in ComponentA. But this does not really work.

It works when I'm using a non-dynamic/concrete/imported component (ConcreteComponent in the code example).

ComponentA:

<script>
import { type ComponentType} from "svelte";
import { ConcreteComponent } from "./ConcreteComponent.svelte"

export let components:ComponentType[];
export let component: ComponentType;

function handleMessage(event: CustomEvent<{text:string}>) {
        console.log(event.detail.text);
    }

</script>

<ConcreteComponent on:customTestEvent={handleMessage}/> //works

<svelte:component this={component} on:customTestEvent={handleMessage}/> //does not work

DynamicComponent:

<!-- DynamicComponent -->
<script>
    import { createEventDispatcher } from 'svelte';

    const dispatch = createEventDispatcher<{ customTestEvent: {text:string}}>();

    function raiseEvent() {
      dispatch("customTestEvent", {text: "Dynamic!"});
    }
</script>

ConcreteComponent:

<script>
    import { createEventDispatcher } from 'svelte';

    const dispatch = createEventDispatcher<{ customTestEvent: {text:string}}>();

    function raiseEvent() {
      dispatch("customTestEvent", {text: "Concrete!"});
    }
</script>

How can I catch an event that has been thrown from a dynamic component?

1

There are 1 best solutions below

0
brunnerh On

Adding on:event handlers to svelte:component works just fine.
You must have misspelled something like the event name, the handler or something else.
Or the component just did not load/be passed at all (but that should be apparent if the component has content).

(In your example there is no handleEvent.)