-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
64 lines (59 loc) · 1.78 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import morphdom from "morphdom";
export class App {
#state;
#taskListDom;
constructor(state, taskListDom, formElement) {
this.#state = state;
this.#taskListDom = taskListDom;
taskListDom.addEventListener("click", this.#eventHandler.bind(this));
formElement.addEventListener("submit", this.#eventHandler.bind(this));
}
render() {
const newTaskListDom = document.createElement("div");
const taskListHTML = this.#state.items
.reduce((html, task) => {
html.push(
`<li class="list__item">
<input
title="Mark done"
class="list__item-checkbox"
type="checkbox"
name="${task.name}"
id="${task.id}"
${task.completed ? "checked" : ""}
/>
<span class="list__item-text">${task.name}</span>
<button
title="Delete task"
class="list__item-remove"
data-task-id="${task.id}"
type="button"
></button>
</li>`
);
return html;
}, [])
.join("");
newTaskListDom.innerHTML = taskListHTML;
morphdom(this.#taskListDom.children[0], newTaskListDom);
}
async #eventHandler(event) {
try {
if (event.type === "submit") {
event.preventDefault();
await this.#state.addItem(new FormData(event.target).get("task-name"));
event.target.reset();
this.render();
} else if (event.target.type === "checkbox") {
await this.#state.updateItem(event.target.id, {
completed: event.target.checked,
});
} else if (event.target.type === "button") {
await this.#state.deleteItem(event.target.dataset.taskId);
this.render();
}
} catch (error) {
console.log(error);
}
}
}