concept dev in category svelte

appears as: dev
Svelte and Sapper in Action

This is an excerpt from Manning's book Svelte and Sapper in Action.

  • Enter npm install.
  • Enter npm run dev to run the app in development mode.

    <script>
      import Todo from './Todo.svelte';
     
      let lastId = 0;
     
      const createTodo = (text, done = false) => ({id: ++lastId, text, done}); #1
     
      let todoText = '';
     
      let todos = [                                                            #2
        createTodo('learn Svelte', true),
        createTodo('build a Svelte app')
      ];
     
      $: uncompletedCount = todos.filter(t => !t.done).length;                 #3
     
      $: status = `${uncompletedCount} of ${todos.length} remaining`;          #4
     
      function addTodo() {
        todos = todos.concat(createTodo(todoText));
        todoText = ''; // clears the input
      }
     
      function archiveCompleted() {
        todos = todos.filter(t => !t.done);                                    #5
      }
     
      function deleteTodo(todoId) {
        todos = todos.filter(t => t.id !== todoId);                            #6
      }
     
      function toggleDone(todo) {
        const {id} = todo;
        todos = todos.map(t => (t.id === id ? {...t, done: !t.done} : t));
      }
    </script>
     
    <div>
      <h1>To Do List</h1>
      <div>
        {status}
        <button on:click={archiveCompleted}>Archive Completed</button>
      </div>
      <form on:submit|preventDefault>                                          #7
        <input
          size="30"
          placeholder="enter new todo here"
          bind:value={todoText} />
        <button disabled={!todoText} on:click={addTodo}>Add</button>           #8
      </form>
      <ul>
        {#each todos as todo}                                                  #9
          <Todo                                                                #10
            {todo}
            on:delete={() => deleteTodo(todo.id)}
            on:toggleDone={() => toggleDone(todo)} />
        {/each}
      </ul>
    </div>
     
    <style>
      button {
        margin-left: 10px;
      }
     
      ul {
        list-style: none; /* removes bullets */
        margin-left: 0;
        padding-left: 0;
      }
    </style>