08: Set Edit Mode

Let's work edit title for each todo. Firstly, change edit mode by double click.

"To save edit results" and "To exit edit mode" are explained in the next section.

Please check below two points.

  1. Cannot return to a view mode after switching to edit mode.
  2. After double-clicking, the edit input field does not get focus automatically.

  1. Add editingTodoIndex with default value as -1 into x-state.
  2. Add editTodo invocation to controller element by x-invocations directive.
  3. Add index variable name into x-each directive for editing each todo item.
  4. Add class binding directive to apply CSS class of editing item design to the todo item.
  5. Add event listener to call editTodo invocation on double click at todo title.
  6. Bind value to <input> of editing todo by x-bind:value. This value does not need as reactive. Only receiving value from controller.

<body>
  <section class="todoapp"
    x-state="{
      todos: [],
      editingTodoIndex: -1,
    }"
    x-invocations="{
      addTodo (_, payload, meta) {

      },
      editTodo (_, payload, meta) {
        const todo = this.todos[payload.index]
        if (!todo) {
          return
        }

        this.beforeEditCache = todo.title
        this.editingTodoIndex = payload.index
      },
    }"
  ::>

    <section class="main">

      <ul class="todo-list"
        x-each="todo, index in todos"
      >
        <li class="todo"
          :class="{
            completed: todo.completed,
            editing: index === editingTodoIndex,
          }"
        >
          <div class="view">

            <label @dblclick="editTodo({index})">{{ todo.title }}</label>
            <button class="destroy"></button>
          </div>
          <input class="edit"
            :value="todo.title"
          >
        </li>
      </ul>
    </section>

  </section>
</body>
</html>