-
Notifications
You must be signed in to change notification settings - Fork 2
/
local_tapas_controller.js
57 lines (48 loc) · 1.33 KB
/
local_tapas_controller.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
import { Controller } from "stimulus";
export default class extends Controller {
static targets = ["itemsList", "input", "form"];
connect() {
this.render();
}
submit(e) {
e.preventDefault(); // prevent from refreshing the page on submit
const item = { name: this.inputTarget.value, checked: false };
this.items.push(item);
this.formTarget.reset();
this.storage = this.items;
this.render();
}
check(e) {
const index = e.target.dataset.index;
this.items[index].checked = !this.items[index].checked;
this.storage = this.items;
}
clear(e) {
this.storage = [];
this.render();
}
render() {
this.items = this.storage;
const html = this.items.reduce((html, item, index) => {
return (html += this.itemHTML(item.name, item.checked, index));
}, "");
this.itemsListTarget.innerHTML = html;
}
itemHTML(name, checked, index) {
const html = `
<li>
<input type="checkbox" data-action="local-tapas#check" data-index="${index}" id="item${index}" ${
checked ? "checked" : ""
}>
<label for="item${index}">${name}</label>
</li>
`;
return html;
}
get storage() {
return JSON.parse(window.localStorage.getItem("myItems")) || [];
}
set storage(items) {
window.localStorage.setItem("myItems", JSON.stringify(items));
}
}