Hrvoje
Hrvoje

Reputation: 119

Svelte 5 and this is undefined

Why I have for this input undefined? Type something and press tab or enter. Svelte is v5.1.3 and I am sure that something is missing.

<script lang="ts">
    let abc11 = $state("");
    
    const izmjeni = (event: HTMLInputElement, data: string) => {
        console.log(event);
        console.log(data);
    }
</script>

<input
    onchange={() => izmjeni(this, "apiData")}
    bind:value={abc11}
    type="text"
/>

Playground

Upvotes: 0

Views: 159

Answers (1)

brunnerh
brunnerh

Reputation: 185180

this is not bound in arrow functions.

Either use a function or define the event object and use event.target/event.currentTarget.

<input onchange={function () { izmjeni(this, "apiData") }} ...>
<input onchange={e => izmjeni(e.target, "apiData")} ...>

Playground

(Would generally not recommend using this, it's non-descriptive and has corner cases like this one.)

Upvotes: 1

Related Questions