In this post, we will learn how to perform inline event handling in Svelte. This type of event handling becomes useful in case we want to perform some action for a list item when user clicks that particular list item on the screen.
This post derives from our previous post about Svelte Keyed Each Block. If you wish to know more about each blocks in Svelte, you can check out that post.
1 – Normal Event Handling
Let’s first understand how we handle click events in Svelte. Check out the below example:
<script>
let books = [{
id: 1,
bookName: "Eye of the World",
},
{
id: 2,
bookName: "The Way of Kings",
},
{
id: 3,
bookName: "The Name of the Wind",
}]
function deleteBook(id) {
console.log(id)
}
</script>
<main>
<h1>Welcome to the Fantasy Library</h1>
{#each books as book (book.id)}
<h4>{book.bookName}</h4>
<button on:click={deleteBook(book.id)}>Delete</button>
{/each}
</main>
We have an array that stores a list of books. We use keyed each block to render the list of books. For each book, we provide a button to delete the book. Basically, we use the on:click to react to the user click by invoking the deleteBook() function with the id of the book.
On paper, this might look fine. However, if you run the application now and visit the developer console, you will see the book ids for the 3 books already printed. Even when the user has not clicked the Delete button, the deleteBook() function executed for each book in the list.
2 – Inline Event Handling
Svelte invokes the function straight away when pass parameters to it as part of the on:click directive.
So how do we get around this issue?
We need to simply wrap the handler function call into another function.
See below change to our example:
<script>
let books = [{
id: 1,
bookName: "Eye of the World",
},
{
id: 2,
bookName: "The Way of Kings",
},
{
id: 3,
bookName: "The Name of the Wind",
}]
function deleteBook(id) {
books = books.filter((book) => book.id != id)
}
</script>
<main>
<h1>Welcome to the Fantasy Library</h1>
{#each books as book (book.id)}
<h4>{book.bookName}</h4>
<button on:click={() => deleteBook(book.id)}>Delete</button>
{/each}
</main>
As you can see, we call the deleteBook function within the arrow function and pass the book id as the argument. In the deleteBook() function, we use the Javascript filter() function to remove the book with matching id.
Another important point to note is that we specifically use the assignment operator (=) for the books array. This is to trigger Svelte’s reactive behaviour. You can read more about it in this post on Svelte Reactivity.
Conclusion
With this, we have successfully learnt how to perform inline event handling in Svelte.
If you have any comments or queries about this post, please feel free to mention them in the comments section below.
0 Comments