-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.vanilla.js
More file actions
99 lines (80 loc) · 2.19 KB
/
Copy pathindex.vanilla.js
File metadata and controls
99 lines (80 loc) · 2.19 KB
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
export function init () {
const LOCAL_STORAGE_KEY = 'items'
const Storage = {
LocalStorage: window.localStorage,
get [LOCAL_STORAGE_KEY] () {
return JSON.parse(this.LocalStorage.getItem(LOCAL_STORAGE_KEY)) || []
},
set [LOCAL_STORAGE_KEY] (value) {
if (typeof value !== 'string') {
value = JSON.stringify(value)
}
this.LocalStorage.setItem(LOCAL_STORAGE_KEY, value)
}
}
const addItems = document.querySelector('.add-items')
const actItems = document.querySelector('.act-items')
const itemsList = document.querySelector('.plates')
const items = Storage[LOCAL_STORAGE_KEY]
function addItem (e) {
e.preventDefault()
const text = (this.querySelector('[name=item]')).value
items.push({
text,
done: false
})
renderList(items, itemsList)
Storage.items = items
this.reset()
}
function renderList (plates = [], platesList) {
platesList.innerHTML = plates.map((plate, i) => {
return `
<li>
<input type="checkbox" data-index="${i}" id="item${i}" ${plate.done ? 'checked' : ''}/>
<label for="item${i}">${plate.text}</label>
</li>
`
}).join('')
}
function toggleDone (index) {
const item = items[index]
item.done = !item.done
renderList(items, itemsList)
Storage.items = items
}
function clearItems () {
items.splice(0)
Storage[LOCAL_STORAGE_KEY] = items
renderList(items, itemsList)
}
function toggleAll (checked) {
items.forEach((item, index) => {
items[index].done = !checked
toggleDone(index)
})
}
addItems.addEventListener('submit', addItem)
itemsList.addEventListener('click', e => {
if (!e.target.matches('input[type=checkbox]')) {
return
}
toggleDone(e.target.dataset.index)
})
actItems.querySelectorAll('button').forEach(btn => btn.addEventListener('click', e => {
switch (e.target.dataset.act) {
case 'clearItems':
clearItems()
break
case 'checkAll':
toggleAll(true)
break
case 'uncheckAll':
toggleAll(false)
break
default:
break
}
}))
renderList(items, itemsList)
}