Skip to content

Instantly share code, notes, and snippets.

@miXwui
Created May 19, 2020 21:52
Show Gist options
  • Save miXwui/0b29c5c4420d20b7856f652c328ed2ed to your computer and use it in GitHub Desktop.
Save miXwui/0b29c5c4420d20b7856f652c328ed2ed to your computer and use it in GitHub Desktop.
Svelte each block bindings with immutable array
<!-- https://svelte.dev/tutorial/each-block-bindings -->
<script>
let todos = [
{ done: false, text: 'finish Svelte tutorial' },
{ done: false, text: 'build an app' },
{ done: false, text: 'world domination' }
];
function changeTodos(idx, values) {
todos = todos.map((t, i) => {
if (i === idx) {
return { ...t, ...values };
}
return t;
})
}
function change(e) {
changeTodos(
parseInt(e.target.attributes.idx.value),
{ done: e.target.checked }
);
}
function input(e) {
changeTodos(
parseInt(e.target.attributes.idx.value),
{ text: e.target.value }
);
}
function add() {
todos = todos.concat({ done: false, text: '' });
}
function clear() {
todos = todos.filter(t => !t.done);
}
$: remaining = todos.filter(t => !t.done).length;
</script>
<style>
.done {
opacity: 0.4;
}
</style>
<h1>Todos</h1>
{#each todos as todo, idx}
<div class:done={todo.done}>
<input
type=checkbox
checked={todo.done}
on:change={change}
idx={idx}
>
<input
placeholder="What needs to be done?"
value={todo.text}
on:input={input}
idx={idx}
>
</div>
{/each}
<p>{remaining} remaining</p>
<button on:click={add}>
Add new
</button>
<button on:click={clear}>
Clear completed
</button>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment