Bindings

Data binding is keeping your application state and user interface synchronized.

Svelte supports data binding using the bind: directive.

Often you have a value that other parts depend on for example if you had a text search input and want to filter a list of items whenever the user types a search query.

You can implement data binding in JavaScript but it’s not part of the language so you often get the value from the event. This is true for other JavaScript frameworks like React that use a synthetic event system and doesn’t have data binding.

Filtering a list of items using JavaScript.

Example.htmlCopy

<input type="text" />
<ul></ul>

<script>
  let list = ['React', 'Vue', 'Svelte']
  let filteredList = []

  let inputElement = document.querySelector('input')
  let listElement = document.querySelector('ul')

  function filterList(event) {
    let searchQuery = event.target.value
    filteredList = list.filter(item => {
      return item
              .toLowerCase()
              .includes(searchQuery.toLowerCase())
    })
    updateUI()
  }

  function updateUI() {
    listElement.innerHTML = filteredList.map(item =>
			`<li>${item}</li>`).join('')
  }

  inputElement.addEventListener('input', filterList)
</script>

Instead of using event.target.value which we could also do in Svelte we can bind the value of the text input field to searchQuery instead.

App.svelteCopy

<script>
 	let list = ['React', 'Vue', 'Svelte']
  let filteredList = []
	let searchQuery = ''

	function filterList() {
    filteredList = list.filter(item => {
      return item
              .toLowerCase()
              .includes(searchQuery.toLowerCase())
    })
  }
</script>

<input
	on:input={filterList}
	bind:value={searchQuery}
	type="text"
/>

<ul>
{#each filteredList as item}
  <li>{item}</li>
{/each}
</ul>

You can have text, numeric, checkbox, group and textarea among other bindings. Instead of overwhelming you with examples you lack context for to find useful right now you can learn more about bindings in the Svelte documentation or by following the Svelte tutorial when you encounter it in your project.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *