-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlocalStorage.js
More file actions
63 lines (60 loc) · 1.42 KB
/
localStorage.js
File metadata and controls
63 lines (60 loc) · 1.42 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
_.storage = {
_prefix: 'prefix_',
_debug: true,
check: function () {
return _.isUndefined(localStorage) ? false : true;
},
get: function (key, hasPrefix) {
if (!this.check()) return;
key = (!hasPrefix) ? this._key(key) : key;
return this.onGet(localStorage.getItem(key));
},
getAll: function () {
if (!this.check()) return ({});
var self = this;
var items = _.map(_.keys(localStorage), function (key) {
return self.get(key, true);
});
return items;
},
set: function (key, value) {
if (!this.check()) return;
try {
this.remove(key);
localStorage.setItem(this._key(key), this.onSet(value));
return true;
} catch (e) {
return false;
}
},
remove: function (key) {
if (!this.check()) return;
localStorage.removeItem(this._key(key));
},
removeByKeyContains: function (key) {
if (!this.check()) return;
_.each(_.keys(localStorage), function (e) {
if (e.indexOf(key) >= 0) this.remove(e);
}, this);
},
clear: function () {
if (!this.check()) return;
localStorage.clear();
},
onSet: function (value) {
return _.isFunction(value) ? null : _.isObject(value) || _.isArray(value) ? JSON.stringify(value) : value;
},
onGet: function (value) {
try {
value = JSON.parse(value);
} catch (e) {
if ( this._debug ) {
console.error(e);
}
}
return value;
},
_key: function (key) {
return this._prefix + (_.isArray(key) || _.isObject(key) ? key.join(".") : key);
}
};