-
Notifications
You must be signed in to change notification settings - Fork 0
/
script-es6.js
107 lines (78 loc) · 2.59 KB
/
script-es6.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
{ // eigener Block um globalen Raum nicht unnötig zu verschmutzen
document.addEventListener('DOMContentLoaded', initialize);
function initialize() {
const input = document.querySelector('input');
const liste = document.querySelector('ul');
const oldTodos = JSON.parse(localStorage.getItem('todos')) || [];
const todoList = new TodoList(liste);
oldTodos.forEach((data) => todoList.createTodo(data));
input.addEventListener('keydown', (event) => {
if (event.keyCode !== 13) return;
const data = {
title: input.value,
isDone: false,
};
todoList.createTodo(data);
input.value = '';
});
}
// ------------------------------------------------------------
class TodoList {
constructor(element) {
this.todos = [];
this.element = element;
}
createTodo(data = {}) {
const todo = new Todo(data, this.todos);
this.todos.push(todo);
const todoElement = todo.render();
todoElement.addEventListener('click', () => this.persist());
this.element.appendChild(todoElement);
this.persist();
}
persist() {
const todos = this.todos.map(todo => todo.toJSON());
const json = JSON.stringify(todos);
localStorage.setItem('todos', json);
}
}
// ------------------------------------------------------------
class Todo {
constructor({ title = '', isDone = false }, collection = []) {
this.title = title;
this.isDone = isDone;
this.collection = collection;
this.element = document.createElement('li');
this.element.addEventListener('click', (event) => {
if (event.target.nodeName === 'BUTTON') {
this.remove();
}
else {
this.toggle();
}
});
}
remove() {
const index = this.collection.indexOf(this);
this.collection.splice(index, 1);
this.element.parentNode.removeChild(this.element);
}
render() {
const checked = this.isDone ? 'checked' : '';
this.element.innerHTML = `<input type="checkbox" ${checked}>${this.title}<button>❌</button>`;
this.element.classList.toggle('done', this.isDone);
return this.element;
}
toggle() {
this.isDone = !this.isDone;
this.render();
}
toJSON() {
const data = {
title: this.title,
isDone: this.isDone,
};
return data;
}
}
}