Part 3 / Advanced bindings / Each block bindings
You can even bind to properties inside an each
block.
App.svelte
{#each todos as todo}
<input
type=checkbox
bind:checked={todo.done}
>
<input
placeholder="What needs to be done?"
bind:value={todo.text}
>
{/each}
Note that interacting with these
<input>
elements will mutate the array. If you prefer to work with immutable data, you should avoid these bindings and use event handlers instead.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<script>
let todos = [
{
done: false,
text: 'finish Svelte tutorial'
},
{ done: false, text: 'build an app' },
{ done: false, text: 'world domination' }
];
function add() {
todos = todos.concat({
done: false,
text: ''
});
}
function clear() {
todos = todos.filter((t) => !t.done);
}
$: remaining = todos.filter(
(t) => !t.done
).length;
</script>
<h1>Todos</h1>
{#each todos as todo}
<div class:done={todo.done}>
<input type="checkbox" checked={todo.done} />
<input
placeholder="What needs to be done?"
value={todo.text}
/>
</div>
{/each}
<p>{remaining} remaining</p>
<button on:click={add}> Add new </button>
<button on:click={clear}>
Clear completed
</button>
<style>
.done {
opacity: 0.4;
}
</style>
initialising