DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Running a Self-Hosted WAF in Production: Practical Lessons From SafeLine
  • How Much Signal Differential Privacy Takes From Your Dashboards, in Events
  • Consumer Lag Is the Wrong Finish Line
  • The Telemetry Tax: Architecting Zero-Allocation Event Observability at 15B+ Daily Event Scale

Trending

  • One Database, Two Models: Building AI-Friendly Java Applications With MySQL JSON Duality Views
  • Why Spark Executors Leave Cores Idle on YARN: A Packing Model for Executor Sizing
  • Solving Comprehension Debt in AI-Generated Codebases
  • Avoiding AI Debt as a Team

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

How To Do Inline Event Handling in Svelte?

In this post, we will learn how to perform inline event handling in Svelte in cases where we want to perform some action for a list item.

By 
Saurabh Dashora
DZone Core CORE ·
Jan. 30, 22 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
6.1K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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 the 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 block in Svelte, you can check out this 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's 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 is executed for each book in the list.

2 – Inline Event Handling

Svelte invokes the function straight away when we 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.

NOTE - The filter() function basically goes through each element in the list and returns a value of true and false. If the returned value is true, the item is added to the list. Else it is removed. In this case, we compare the id of the current book with the input id of the function. If the two ids do not match, the condition becomes true and the book is kept in the array. When the two ids match, the condition becomes false and the corresponding book is removed from the list.

Another important point to note is that we specifically use the assignment operator (=) for the books array. This is to trigger Svelte’s reactive behavior. You can read more about it in this post on Svelte Reactivity.

Conclusion

With this, we have successfully learned 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.

Svelte Event Book

Published at DZone with permission of Saurabh Dashora. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Running a Self-Hosted WAF in Production: Practical Lessons From SafeLine
  • How Much Signal Differential Privacy Takes From Your Dashboards, in Events
  • Consumer Lag Is the Wrong Finish Line
  • The Telemetry Tax: Architecting Zero-Allocation Event Observability at 15B+ Daily Event Scale

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook