11: Cancel Edit Todo
Let's work to cancel edit mode by pressing ESC key.
- Add keyup event listener to <input> of edit todo by x-on:keyup.esc directive. It calls cancelEdit invocation on escape-key only.
<body> <section class="todoapp"<!DOCTYPE html>
<html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width,initial-scale=1" > <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/todomvc-app-css@2.1.2/index.css" > <script src="https://x-ninja.org/assets/js/o_o.js"></script> <script src="https://x-ninja.org/assets/js/flux._.js"></script> <title>TODOs @x-ninja</title> </head>x-state="{
todos: [], editingTodoIndex: -1, }"doneEdit (_, payload, meta) {x-invocations="{
addTodo (_, payload, meta) { const newTodo = payload.newTodo.trim() if (!newTodo) { return } this.todos.push({ title: newTodo, completed: false }) }, editTodo (_, payload, meta) { const todo = this.todos[payload.index] if (!todo) { return } this.beforeEditCache = todo.title this.editingTodoIndex = payload.index }, focusTodo (_, payload, meta) { const inputs = _.$.querySelectorAll('input.edit') const target = inputs[payload.index] if (!target) { return } target.focus() target.setSelectionRange( target.value.length, target.value.length ) },}, cancelEdit (_, payload, meta) { this.editingTodoIndex = -1 }, }" ::>const todo = this.todos[payload.index]
if (!todo) { return } if (this.editingTodoIndex === -1) { return } this.editingTodoIndex = -1 const newTitle = meta._.$.value.trim() if (newTitle) { todo.title = newTitle }<section class="main"><header class="header">
<h1>todos</h1> <input class="new-todo" autofocus autocomplete="off" placeholder="What needs to be done?" @change="addTodo({newTodo: launcher$.value})" x-callbacks="{ change (_) { _.$.value = '' } }" > </header><ul class="todo-list" x-each="todo, index in todos" ><input id="toggle-all" class="toggle-all" type="checkbox">
<label for="toggle-all">Mark all as complete</label><li class="todo"
:class="{ completed: todo.completed, editing: index === editingTodoIndex, }" ><input class="edit" :value="todo.title" @change="doneEdit({index})" @keyup.esc="cancelEdit" > </li> </ul> </section><div class="view">
<input class="toggle" type="checkbox" x-model="todo.completed" > <label @dblclick="editTodo({index}), focusTodo({index})">{{ todo.title }}</label> <button class="destroy"></button> </div></section> </body> </html><footer class="footer">
<span class="todo-count"> <strong>3</strong> items left </span> <ul class="filters"> <li><a href="#/all" class="selected">All</a></li> <li><a href="#/active">Active</a></li> <li><a href="#/completed">Completed</a></li> </ul> <button class="clear-completed"> Clear completed </button> </footer>