-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.ts
77 lines (69 loc) · 2.09 KB
/
script.ts
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
import { IdbApi } from "../src/idbClass";
const idb = new IdbApi();
type data = {
["value"]: string;
};
const DATA_DISPLAYER_ID = "data";
const ADD_BTN_ID = "add";
const GET_BTN_ID = "get";
const UPD_BTN_ID = "upd";
const DEL_BTN_ID = "del";
function FindElOrThrow<T>(selector: string): T {
const el = document.getElementById(selector) as T;
if (!el) {
throw new Error(`could not find div with id: ${selector}`);
}
return el;
}
const dataDisplayer = FindElOrThrow<HTMLDivElement>(DATA_DISPLAYER_ID);
const addBtn = FindElOrThrow<HTMLButtonElement>(ADD_BTN_ID);
const getBtn = FindElOrThrow<HTMLButtonElement>(GET_BTN_ID);
const updBtn = FindElOrThrow<HTMLButtonElement>(UPD_BTN_ID);
const delBtn = FindElOrThrow<HTMLButtonElement>(DEL_BTN_ID);
addBtn.addEventListener(
"click",
function ({ target }: Event, payload?: string) {
let data = (target as HTMLButtonElement).getAttribute("data-payload");
if (payload) {
data = payload;
}
idb.addData({ value: data });
},
);
getBtn.addEventListener(
"click",
async function ({ target }: Event, payload?: number) {
let key = parseInt(
(target as HTMLButtonElement).getAttribute("data-key") || "1",
10,
);
if (payload) {
key = payload;
}
const data = await idb.getData<data>(key);
dataDisplayer.innerText = data.value;
},
);
updBtn.addEventListener(
"click",
async function ({ target }: Event, key?: number, payload?: string) {
const targetBtn = target as HTMLButtonElement;
const dataKey = parseInt(targetBtn.getAttribute("data-key") || "1", 10);
const dataPayload = targetBtn.getAttribute("data-payload") as string;
idb.updateData<data>((oldData) => {
oldData.value = payload || dataPayload;
return oldData;
}, key || dataKey);
const data = await idb.getData<data>(key || dataKey);
dataDisplayer.innerText = data.value;
},
);
delBtn.addEventListener(
"click",
async function ({ target }: Event, key?: number) {
const targetBtn = target as HTMLButtonElement;
const dataKey = parseInt(targetBtn.getAttribute("data-key") || "1", 10);
idb.deleteData(key || dataKey);
dataDisplayer.innerText = "data deleted";
},
);