Skip to content

Instantly share code, notes, and snippets.

@QuocCao-dev
Created April 25, 2024 14:02
Show Gist options
  • Save QuocCao-dev/c794a0cfbc5885c3e1ac3e0b1f432cee to your computer and use it in GitHub Desktop.
Save QuocCao-dev/c794a0cfbc5885c3e1ac3e0b1f432cee to your computer and use it in GitHub Desktop.
TodoProjectList
class Todo {
constructor(text, finished) {
this.id = String(Date.now());
this.text = text;
this.finished = finished;
}
}
class InputDOM {
constructor() {
this.inputDOM = undefined;
}
getInputValue() {
this.inputDOM = document.querySelector(".input");
return this.inputDOM.value;
}
clearInput() {
this.inputDOM.value = "";
}
}
class FormDOM {
constructor() {
this.formDOM = document.querySelector(".form");
this.listDOM = document.querySelector(".list");
}
addLiToList(todo) {
const liTag = this.createLiTag(todo);
this.listDOM.appendChild(liTag);
}
createLiTag(todo) {
const li = document.createElement("li");
if (todo.finished) li.classList.add("checked");
const checkedIcon = document.createElement("i");
checkedIcon.classList.add("fas", "fa-check-square");
const trashIcon = document.createElement("i");
trashIcon.classList.add("fas", "fa-trash");
li.appendChild(document.createTextNode(todo.text));
li.appendChild(checkedIcon);
li.appendChild(trashIcon);
checkedIcon.addEventListener("click", () => {
li.classList.toggle("checked");
fetch("http://localhost:3000/todoList/" + todo.id, {
method: "PATCH",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
text,
finished: !todo.finished,
}),
});
});
trashIcon.addEventListener("click", () => {
li.remove();
fetch("http://localhost:3000/todoList/" + todo.id, {
method: "DELETE",
});
});
return li;
}
renderList(todos) {
todos.forEach((todo) => {
this.addLiToList(todo);
});
}
submit() {
this.formDOM.addEventListener("submit", (e) => {
e.preventDefault();
const input = new InputDOM();
const todo = new Todo(input.getInputValue(), false);
this.addLiToList(todo);
input.clearInput();
fetch("http://localhost:3000/todoList", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(todo),
});
});
}
}
document.addEventListener("DOMContentLoaded", function () {
const formDOM = new FormDOM();
fetch("http://localhost:3000/todoList")
.then((res) => res.json())
.then((data) => {
formDOM.renderList(data);
});
formDOM.submit();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment