-
Notifications
You must be signed in to change notification settings - Fork 1
/
store.js
99 lines (85 loc) · 2.7 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
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
//
// Copyright (c) 2011 Frank Kohlhepp
// https://github.com/frankkohlhepp/store-js
// License: MIT-license
//
(function () {
var Store = this.Store = function (name, defaults) {
var key;
this.name = name;
if (defaults !== undefined) {
for (key in defaults) {
if (defaults.hasOwnProperty(key) && this.get(key) === undefined) {
this.set(key, defaults[key]);
}
}
}
};
Store.prototype.get = function (name) {
name = "store." + this.name + "." + name;
if (localStorage.getItem(name) === null) { return undefined; }
try {
return JSON.parse(localStorage.getItem(name));
} catch (e) {
return null;
}
};
Store.prototype.set = function (name, value) {
if (value === undefined) {
this.remove(name);
} else {
if (typeof value === "function") {
value = null;
} else {
try {
value = JSON.stringify(value);
} catch (e) {
value = null;
}
}
localStorage.setItem("store." + this.name + "." + name, value);
}
return this;
};
Store.prototype.remove = function (name) {
localStorage.removeItem("store." + this.name + "." + name);
return this;
};
Store.prototype.removeAll = function () {
var name,
i;
name = "store." + this.name + ".";
for (i = (localStorage.length - 1); i >= 0; i--) {
if (localStorage.key(i).substring(0, name.length) === name) {
localStorage.removeItem(localStorage.key(i));
}
}
return this;
};
Store.prototype.toObject = function () {
var values,
name,
i,
key,
value;
values = {};
name = "store." + this.name + ".";
for (i = (localStorage.length - 1); i >= 0; i--) {
if (localStorage.key(i).substring(0, name.length) === name) {
key = localStorage.key(i).substring(name.length);
value = this.get(key);
if (value !== undefined) { values[key] = value; }
}
}
return values;
};
Store.prototype.fromObject = function (values, merge) {
if (merge !== true) { this.removeAll(); }
for (var key in values) {
if (values.hasOwnProperty(key)) {
this.set(key, values[key]);
}
}
return this;
};
}());