바닐라 JS로 크롬 앱 만들기::복습 7.0~7.8 (작성중)

Jo·2021년 9월 4일
0

7장 To do list 구현

7.0 setup

setup은 4장 greeting이랑 유사하다.

  1. html으로 폼과 input 생성
  2. default값 차단. 작성하면 글이 사라지도록
  3. *사라지기전 변수에 미리 save 해둠
const todoForm=document.getElementById("todo-form");
const todoInput=todoForm.querySelector("input");
const todoList=document.getElementById("todo-list");

function handleTodoSubmit(event){
event.preventDefault();
const newTodo = todoInput.value;
todoInput.value="";
}

todoForm.addEventListener("submit", handleTodoSubmit);

const todoForm=document.getElementById("todo-form"); 일 때,

위와 아래는 같은 뜻이다.
const todoInput=todoForm.querySelector("input");
const todoInput=document.querySelector("#todo-Form input");

7.1 Adding

7.0에서 생성한 변수 newTodo를 새로 정의한 paintTodo()의 인수로 보낸다.
여기서 새로운 list을 추가하는 방법은 6.1 background에서 다룬 것과 유사하다. js->html으로 element를 생성해서 태그를 추가해주는 것이다.
appendChild 개념을 잘 이해할 것

const todoForm=document.getElementById("todo-form");
const todoInput=todoForm.querySelector("input");
const todoList=document.getElementById("todo-list");

function paintTodo(newTodo){
const li=document.createElement("li");
const span=document.createElement("span");
li.appendChild(span);
span.innerText=newTodo;
todoList.appendChild(li);

}

function handleTodoSubmit(event){
event.preventDefault();
const newTodo = todoInput.value;
todoInput.value="";
paintTodo(newTodo);
}

todoForm.addEventListener("submit", handleTodoSubmit);

위와 같이 태그를 잘 추가해주면 다음처럼 list추가가 가능함.

7.2 Deleting

delete 에서 문제 상황 -> delete는 모두 button을 삭제할 때 발생하므로, 우리가 어떤 button을 눌렀을 때 발생하는지 알 수 없음. 그러나 dir을 살펴보면 target.parentElement로 button의 부모 element를 찾을 수 있음. 이를 이용하여 삭제함.

function deleteTodo(event){
const li = event.target.parentElement;
li.remove();
}

*(개인적인 생각) 결론은 간단하지만 이러한 상황에 직면했을 때 어떻게 대처해야하는지 알려주는 것. dir로 알아낼 수 있는 정보값을 최대한 이용해내서 문제를 해결할 것.

7.3 Saving

우선 저장을 위해 todos라는 array를 정의한다. 하지만 localstorage에서는 문자열밖에 저장할 수 없기 때문에 string형태로 고쳐줄 것이 필요한데, js에서는 string형태로 변환해주는 함수를 다음과 같이 정의한다.

JSON.stringify(array)
적용 안했을 때

function saveTodos(){
    localStorage.setItem("todos",todos);

}

적용 했을 때

function saveTodos(){
    localStorage.setItem("todos",JSON.stringify(todos));
}

profile
이것저것 배우고 싶은 대학생

0개의 댓글