Quantcast
Channel: Active questions tagged svelte - Stack Overflow
Viewing all articles
Browse latest Browse all 1541

What is the best way to implement event handling on multiple list of child components in svelte?

$
0
0

Let's say I have a to-do list. Each list item has a delete button which will delete the item from list array if clicked. Now we can use these methods.

1.

//store.tsexport type Item = {    text: string;    id: string;}export const items = writable<Item[]>();
<!-- Item.svelte --><script>    export let id; //I don't want to use id on the html elements. As anyone can change it from inspection tool.    export let text;</script><div> {text} <button on:click={() => {    //handle click event}}> close </button> </div>
<!-- Items.svelte --><script>    import Item from "./Item";    const items = [        {            id: 1,            text: 'Turn on pc'        },        {            id: 2,            text: 'Open VS code'        }    ];</script>{#each items as item}<Item id={item.id} text={item.text} />{/each}

2.

<!-- Items.svelte --><script>    import Item from "./Item";    let container;    function handleClick(node){        node.onclick = (evt) => {            const target = evt.target;            //handle event       }    }    const items = [        {            id: 1,            text: 'Turn on pc'        },        {            id: 2,            text: 'Open VS code'        }    ];</script><div use:handleClick>{#each items as item}<Item id={item.id} text={item.text} />{/each}</div>

I somehow need to get the Object reference we used to build the element inside {#each} block.But as I said I'm not interested using id on html that we can use to grab the element we clicked on.


Viewing all articles
Browse latest Browse all 1541

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>