This video is available to students only

Events and Input Bindings

Using Svelte to handle DOM events and bind inputs

Input Binding#

JavaScript frameworks have come a long way in helping developers handle input binding.

When we say input binding, we mean taking the value from an HTML input and updating an underlying reference variable in JavaScript and inversely, taking values from JavaScript variables and displaying them in inputs. This is sometimes called two-way binding.

Svelte makes input binding easy with the bind:value="{<varname>}" directive on the relevant HTML element.

Let's add value bindings to our Home.svelte components. We need two variables to bind to: emailAddress and schoolName. Then we need to update the markup with bind:value.

First add a <script> section with the two variables to the top of the file:

Then, in the markup section, find the Email Address and School Name inputs and add the bind:value={var} directives:

Now, any time a user updates those inputs, the underlying emailAddress and schoolName variables will be updated.

Likewise, imagine that we have a clear() function that sets emailAddress and schoolName to blank. If we called the clear function and cleared the variables, the inputs would automatically react and also be cleared.

 

This page is a preview of Fullstack Svelte

Please select a discussion on the left.