Svelte like most frontend Javascript frameworks, supports two-way data binding. Data binding is a way of interconnecting an element's attribute to a variable where when the attribute value changes, the change is reflected in the variable and vice versa. Thus they both contain updated values of each other.
In Svelte, data binding can be achieved using the bind
attribute. An example is:
<script>
let name;
</script>
<input type='text' bind:value={name} />
Whenever the value
of the input changes, the value of name reflects this change. This can be useful if we want to display the bound data actively or run some functionality repeatedly like in the input's case, to validate the data actively.
Data binding in Svelte is 2-way
This means that if we change the value of name, the change is reflected in the input's value and vice versa, thus we can programmatically change the value of <input>
this way.
You can bind any attribute from value to src
and the likes. This can allow for easy manipulation of these attributes (i.e, getting and setting their values).
I mostly use binding when validating a form or getting data from an input to store or manipulate, but there are other ways of using this to do stuff. 2-way binding is beneficial in svelte and just makes your life easier.
To learn more, visit the Svelte docs
Michael Nji author
I build interactive web apps using mordern web technologies
2.6k