sveltejs / svelte

Cybernetically enhanced web apps
https://svelte.dev
MIT License
76.98k stars 4k forks source link

docs: svelte 5 event handler pass variables? #11671

Closed MentalGear closed 4 days ago

MentalGear commented 2 weeks ago

Describe the problem

https://svelte-5-preview.vercel.app/docs/event-handlers

The docs do not describe how to pass variables with the event from a subComponent to overlying component.

Describe the proposed solution

Describe in the docs.

Importance

would make my life easier

dummdidumm commented 2 weeks ago

I don't know what exactly you mean. Can you clarify? (It sounds like you mean https://svelte-5-preview.vercel.app/docs/event-handlers#bubbling-events, which is already described)

jamesst20 commented 2 weeks ago

@dummdidumm

While it's pretty easy to guess how to pass parameters using events, I kind of agree there is no "recommended" approach in the doc.

I believe what @MentalGear is trying to say (it's just a guess) is that previously using Svelte 4

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

    const dispatch = createEventDispatcher();
</script>

<button on:click={() => dispatch('notify', 'detail value')}>Fire Event</button>

You could pass the value in the dispatch method ('detail value') and you would fetch it inside the event detail property

<script>
    function callbackFunction(event) {
        console.log(`Notify fired! Detail: ${event.detail}`);
    }
</script>

<Child on:notify={callbackFunction} />

Now with Svelte 5, there is no "documented" way on how you pass custom values and you also lose the "event" unless you pass it yourself.

<script>
        let { onclick } = $props();

    let count = $state(0);

    function handleClick(e) {
                count++;
                onclick?.(count);
    }
</script>

<button onclick={handleClick}>
    clicks: {count}
</button>
<script>
    function callbackFunction(count) {
        console.log(`Click fired! New value: ${count}`);
    }
</script>

<Child onclick={callbackFunction} />