Use Event Handlers in Svelte 2

Andrew Smith
InstructorAndrew Smith
Share this video with your friends

Social Share Links

Send Tweet
Published 5 years ago
Updated 5 years ago

In this lesson you will learn how to attach Event Handlers to buttons and input fields. Event handlers normally follows the on:[event] format. If you are making use of two way binding you should use bind: instead, for example an input field could use bind:value.

Instructor: [00:00] Here, we have this app component that renders a UI for us. It has two data properties, counter and message. We can change the state by updating its value in the data method. We change counter to 10. We should now have 10 items.

[00:14] Let's add an on-click event to the add button. Inside the event handler, let's update the counter state by a call-in set with the value of counter = counter + 1. Let's copy this for the remove button and - 1 from the counter instead. If we click the add, the number of items increase.

[00:33] If we click remove, the number decrease. Let's take a look at the input. Input provides an on-input event which fires each time the input changes. Inside of this event, we will set the value of message to equal the value of the input field. We can now type a value in the input field and see the message update.

[00:54] Now let's take a look at the bind directive. Here, we will bind a value of the input field to the message data property. Now if we type in the field same as before, the message should update.

Veekas Shrivastava
Veekas Shrivastava
~ 5 years ago

Useful and concise, thanks! Are you considering making more svelte lessons?

Andrew Smith
Andrew Smithinstructor
~ 5 years ago

Thank you Veekas, Yes I have more svelte lessons coming up.

Markdown supported.
Become a member to join the discussionEnroll Today