JavaScript学习笔记:使用MVC思想创建一个TODO List
model:页面中的数据层,包括数据获取、增删改查
view:页面中的显示逻辑,包括生成element,追加等
controller:页面中的动作逻辑,控制层逻辑
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>JS中的MVC设计方法</title> </head> <body> <div class="container"> <h1>使用Model View Controller创建一个ToDo List</h1> </div> <section> <input type="text" name="" id="todo-msg-text" placeholder="请输入你要做的事" /> <input type="date" name="" id="todo-msg-date" placeholder="选择日期" /> <button id="add">加入!</button> <div id="todo-list"></div> </section> <script> // model let todos; const savedData = JSON.parse(localStorage.getItem("todos")); if (Array.isArray(savedData)) { todos = savedData; } else { todos = [ { title: "123", dueDate: "2021-10-12", id: "id1", }, { title: "234", dueDate: "2021-11-12", id: "id2", }, ]; } // CRUD const createTodo = (title, dueDate) => { const id = "" + new Date().getTime(); todos.push({ title: title, dueDate: dueDate, id: id, }); saveTodos(); }; const deleteTodo = (id) => { todos = todos.filter((todo) => { if (todo.id === id) return false; else return true; }); saveTodos(); }; // view const render = () => { const todoDiv = document.getElementById("todo-list"); todoDiv.innerHTML = ""; todos.forEach((todo) => { const element = document.createElement("div"); element.innerHTML = todo.title + " " + todo.dueDate; const deleteBtn = document.createElement("button"); deleteBtn.id = todo.id; deleteBtn.onclick = deleteAction; deleteBtn.innerText = "删除"; element.append(deleteBtn); todoDiv.append(element); }); }; // controller const addAction = () => { const title = document.getElementById("todo-msg-text").value; const dueDate = document.getElementById("todo-msg-date").value; createTodo(title, dueDate); render(); }; const deleteAction = (event) => { deleteTodo(event.target.id); render(); }; // other function const saveTodos = () => { localStorage.setItem("todos", JSON.stringify(todos)); }; // 入口 document.getElementById("add").addEventListener("click", addAction); render(); </script> </body> </html>