JavaScript/예제

javascript to do 리스트 응용 (3) localstorage 데이터 삭제

고기고기물고기 2022. 4. 6. 03:34

todo.js

const toDoForm = document.getElementById("todo-form");
const toDoInput = toDoForm.querySelector("input");
const toDoList = document.getElementById("todo-list");

let toDos = [];

const TODOS_KEY = "todos"

function saveToDos(){

    localStorage.setItem("todos", JSON.stringify(toDos));

}

function deleteToDo(event){
  const li = event.target.parentElement;
  todos = todos.filter(toDo => toDo.id !== parseInt(li.id));
   li.remove();
   saveToDos();
}

function paintToDo(newTodo){
    const li = document.createElement("li");
    li.id = newTodo.id;
    const span = document.createElement("span");
    span.innerText= newTodo.text;
    const button = document.createElement("button");
    button.innerText = "✂";
    button.addEventListener("click", deleteToDo)
    li.appendChild(span);
    li.appendChild(button);
    toDoList.appendChild(li);

}

function handleToDoSubmit(event) {
    event.preventDefault();
    const newTodo = toDoInput.value;
    toDoInput.value = "";
    const newTodoObj = {
        text: newTodo,
        id: Date.now()
    }
    toDos.push(newTodoObj);
    paintToDo(newTodoObj);
    saveToDos();
}

toDoForm.addEventListener("submit", handleToDoSubmit)

const getToDos = localStorage.getItem(TODOS_KEY);

if(getToDos !== null){
    const parsedToDos = JSON.parse(getToDos);
    toDos = parsedToDos;
    parsedToDos.forEach(paintToDo);
    // parsedToDos.forEach((item) => console.log("this is the turn of", item));
}

 

 

  • fcunction paintToDo -> 버튼 클릭시 deleteToDo 라는 Function이 실행되도록 이벤트를 만들어준다
  • fcunction deleteToDo -> event.target.parentElement -> 이벤트가 발생한 요소를 반환해준다. 
  • filter -> 지정된 조건에 맞는건만 반환 해준다 (forEach 처럼 배열 length 3개 이면 3번 실행한다)
  • 이벤트 발생한 요소를 삭제 후 localStorage에 다시 저장한다.