Svelte: Svelte this click events

Created on 19 Jun 2019  路  4Comments  路  Source: sveltejs/svelte

I'm playing around with d3 and Svelte, using the d3-geo package to create maps.

When doing click events, this returns {d: {鈥, i: number} and not the path as one would might expect. With Svelte, how would one access the path then? Does it have to do with the fact that the script is first, and the the HTML + markup after that is causing problems?

On the bright side, like in react, doing events like this n:click={() => clickedState(d)} works.

<svg width={width} height={height}>
    <g> 
    {#each data as d, i} 
        <path
            fill={fill}
            stroke="#333"
            d={geo(d)}
            on:click={() => clickedState(d)}
            on:mouseover={() => {
                hoverState(d)
                console.log(this)
                // console.log(this).attr('class', 'state colored')
            }}
            on:mouseout={() => hoverStateOut(d)}
        ></path>
    {/each}
    </g>
</svg>

Most helpful comment

Use e.target (e.currentTarget) rather than this. See how arrow functions works. It's not a svelte's problem

All 4 comments

Use e.target (e.currentTarget) rather than this. See how arrow functions works. It's not a svelte's problem

This is quite weird actually, can you reproduce this in a REPL?

Inline arrow function event handlers get compiled to normal functions in Svelte, not arrow functions (see this REPL, look for click_handler in the js output, this behaves normally).

As @qutran said, the solution is to use e.currentTarget, it is generally a safer solution than relying on this in event handlers but I'm curious as to why this is happening.

e.currentTarget worked. Thanks for the suggestion!

@Leschonander if ok please close the issue.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

thoughtspile picture thoughtspile  路  3Comments

st-schneider picture st-schneider  路  3Comments

plumpNation picture plumpNation  路  3Comments

matt3224 picture matt3224  路  3Comments

noypiscripter picture noypiscripter  路  3Comments