Chris
Chris

Reputation: 1475

Accessing data from mouse event in Svelte

I'm trying to get a tooltip to work with data that is used to drive a series of svg elements, in this case circles.

I can see e.target.data contains the data, but I am unsure whether this is best practice. Are there any issues in using it? I can't see it anywhere in e.currentTarget.

Interestingly, when I replicate the below in Svelte REPL, e.target.data returns undefined.

https://svelte.dev/repl/ae8e3d3c913642db98e774519e9da2f8?version=3.52.0

<script>
    import * as d3 from "d3";
    export let data = [{id:1, x:50, y:50, firstName:"Fred"},
                       {id:2, x:100, y:100, firstName: "Mary"}]
    
    function handleMouseover(e) {
        console.log(e.currentTarget.attributes) // Returns named node map. Contains circle attributes but no data
        console.log(e.target.__data__) // contains data
    }
</script>

<svg>
    <g>
        <rect
          width="100%"
          height="100%"
          fill="transparent"
        />
            {#each data as d}
            <circle
                id={d.id}
                cx={d.x}
                cy={d.y}
                r=5
                fill="grey"
                stroke="white"
                on:mouseover|preventDefault={handleMouseover}
            >
            </circle>
        {/each}
    </g>
</svg>

Upvotes: 0

Views: 682

Answers (1)

Corrl
Corrl

Reputation: 7721

With the use of an arrow function you could add d as parameter to the function call like this

on:mouseover|preventDefault={(e) => handleMouseover(e,d)}

(Is there a default behaviour that needs to be prevented..?)

    function handleMouseover(e,d) {
        console.log(d)
    }

Upvotes: 2

Related Questions