Skip to content

Event Handler registration & slot mounting order causes issues #9017

@peterkogo

Description

@peterkogo

Describe the bug

When there are 2 nested components

<Master>
    <Minion />
</Master>

a Minion, which uses an action that dispatches a Custom Event on mount

// Minion.svelte

<script>
    const dispatchSomeEvent = (node) => {
        // This is called on mount
        console.log('marco')
	
        const someEvent = new CustomEvent('someEvent', { bubbles: true });
        node.dispatchEvent(someEvent);
    }
</script>

<div use:dispatchSomeEvent />

and a Master, which handles the event.

// Master.svelte

<div on:someEvent={(event) => {
    // This SHOULD be called on mount of the child
    console.log('polo')
}}>
    <slot />
</div>

The console printout should be "marco" "polo" - but it is not. The Master never handles the event on initial mount.

Looking at the generated code

m(target, anchor) {
	insert(target, div, anchor);

	if (default_slot) {
		default_slot.m(div, null);
	}

	current = true;

	if (!mounted) {
		dispose = listen(div, "someEvent", /*someEvent_handler*/ ctx[2]);
		mounted = true;
	}
}

the mounting of the slot happens before the event handlers are registered.

Is there are reason for this order?

Reproduction

Link to REPL

Logs

No response

System Info

System independent

Severity

annoyance

Metadata

Metadata

Assignees

No one assigned

    Labels

    compilerChanges relating to the compiler

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions