/
localstorage.go
69 lines (50 loc) · 1.52 KB
/
localstorage.go
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
package localstoragedemo
import (
"github.com/gopherjs/gopherjs/js"
"honnef.co/go/js/dom"
)
var localStorage = js.Global.Get("localStorage")
var D = dom.GetWindow().Document().(dom.HTMLDocument)
func InitializePage() {
saveButton := D.GetElementByID("saveButton").(*dom.HTMLButtonElement)
saveButton.AddEventListener("click", false, func(event dom.Event) {
Save()
})
clearAllButton := D.GetElementByID("clearAllButton").(*dom.HTMLButtonElement)
clearAllButton.AddEventListener("click", false, func(event dom.Event) {
ClearAll()
})
DisplayStorageContents()
}
func Save() {
itemKey := D.GetElementByID("itemKey").(*dom.HTMLInputElement)
itemValue := D.GetElementByID("itemValue").(*dom.HTMLInputElement)
if itemKey.Value == "" {
return
}
SetKeyValuePair(itemKey.Value, itemValue.Value)
itemKey.Value = ""
itemValue.Value = ""
DisplayStorageContents()
}
func ClearAll() {
localStorage.Call("clear")
DisplayStorageContents()
}
func SetKeyValuePair(itemKey string, itemValue string) {
localStorage.Call("setItem", itemKey, itemValue)
}
func DisplayStorageContents() {
itemList := D.GetElementByID("itemList")
itemList.SetInnerHTML("")
for i := 0; i < localStorage.Length(); i++ {
itemKey := localStorage.Call("key", i)
itemValue := localStorage.Call("getItem", itemKey)
dtElement := D.CreateElement("dt")
dtElement.SetInnerHTML(itemKey.String())
ddElement := D.CreateElement("dd")
ddElement.SetInnerHTML(itemValue.String())
itemList.AppendChild(dtElement)
itemList.AppendChild(ddElement)
}
}