하루 하루

[노마드코더] 초보자를 위한 바닐라 자바스크립트 - 13 본문

IT/Web

[노마드코더] 초보자를 위한 바닐라 자바스크립트 - 13

san_deul 2020. 5. 14. 16:24

3-7 Making a To Do List part Three

 

const toDoForm = document.querySelector(".js-toDoForm"),
toDoInput =  toDoForm.querySelector("input"),
toDoList = document.querySelector(".js-toDoList");

const TODOS_LS='toDos';
let toDos =[];

function deleteToDo(event){
  const btn = event.target ;
  const li = btn.parentNode;
  toDoList.removeChild(li);
  const cleanToDos = toDos.filter(function(todo){
    return todo.id !== parseInt(li.id);
  });
  toDos = cleanToDos;
  saveToDos();
}

function saveToDos(){ 
  localStorage.setItem(TODOS_LS,JSON.stringify(toDos));
}
function paintToDo(text){
  const li = document.createElement("li");
  const delBtn = document.createElement("button");
  const span = document.createElement("span");
  const newId = toDos.length + 1;
  delBtn.innerText = "X";
  delBtn.addEventListener("click",deleteToDo);
  span.innerText =text;
  li.appendChild(span);
  li.appendChild(delBtn);
  li.id =newId;
  toDoList.appendChild(li);

  const toDoObj = {
    text: text,
    id: newId 
  };
  toDos.push(toDoObj);
  saveToDos();
}
function handleSubmit(event){
  event.preventDefault(); 
  const currentValue = toDoInput.value;
  paintToDo(currentValue);
  toDoInput.value="";
}
function loadToDos(){
  const loadedToDos = localStorage.getItem(TODOS_LS);
  if(loadedToDos !== null){ 
    const parsedTodo = JSON.parse(loadedToDos);
    parsedTodo.forEach(function(todo){
      paintToDo(todo.text);
    })
  }
}

function init(){
  loadToDos(); 
  toDoForm.addEventListener("submit",handleSubmit);
}

init();

n

Comments