-
Notifications
You must be signed in to change notification settings - Fork 109
/
store.js
61 lines (61 loc) · 1.94 KB
/
store.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
export const TodoStore = class extends EventTarget {
constructor(localStorageKey) {
super();
this.localStorageKey = localStorageKey;
this._readStorage();
// handle if todos are edited in another window
window.addEventListener("storage", () => {
this._readStorage();
this._save();
}, false);
}
_readStorage () {
this.todos = JSON.parse(window.localStorage.getItem(this.localStorageKey) || '[]');
}
_save() {
window.localStorage.setItem(this.localStorageKey, JSON.stringify(this.todos));
this.dispatchEvent(new CustomEvent('save'));
}
// GETTER methods
all (viewFilter) {
if (viewFilter === 'active') {
return this.todos.filter(todo => !todo.completed);
}
if (viewFilter === 'completed') {
return this.todos.filter(todo => todo.completed);
}
return this.todos;
}
hasCompleted () {
return this.todos.some(todo => todo.completed);
}
isAllCompleted () {
return this.todos.every(todo => todo.completed);
}
// MUTATE methods
add (todo) {
this.todos.push({ title: todo.title, completed: false, id: "id_" + Date.now() });
this._save();
}
remove ({ id }) {
this.todos = this.todos.filter(todo => todo.id !== id);
this._save();
}
toggle ({ id }) {
this.todos = this.todos.map(todo => todo.id === id ? { ...todo, completed: !todo.completed } : todo);
this._save();
}
clearCompleted () {
this.todos = this.todos.filter(todo => !todo.completed);
this._save();
}
update (todo) {
this.todos = this.todos.map(t => t.id === todo.id ? todo : t);
this._save();
}
toggleAll () {
const completed = !this.hasCompleted() || !this.isAllCompleted();
this.todos = this.todos.map(todo => ({ ...todo, completed }));
this._save();
}
}