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:
<script>
let emailAddress
let schoolName
</script>
Then, in the markup section, find the Email Address and School Name inputs and add the bind:value={var}
directives:
<div class="control">
<!-- HERE!!!! -->
<input
bind:value="{emailAddress}"
type="text"
placeholder="Enter your email address"
class="input" />
</div>
</div>
<div class="field">
<label class="label">School Name</label>
<div class="control">
<!-- AND HERE!!!! -->
<input
bind:value="{schoolName}"
type="text"
placeholder="Enter your school's name"
class="input" />
</div>
</div>
<div class="field is-grouped">
<div class="control">
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.
DOM Events#
This page is a preview of Fullstack Svelte