-
Notifications
You must be signed in to change notification settings - Fork 4
/
f2-storage.js
86 lines (71 loc) · 1.87 KB
/
f2-storage.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
/**
* F2 Plugin -- Storage v1.0
*
* Facilitates persistent storage of data on the client browser using
* localStorage or cookies, depending on browser support.
*
* (c) 2013 Markit On Demand http://dev.markitondemand.com
*
*/
F2.extend('Storage', (function() {
var _hasLocalStorage = typeof Storage !== 'undefined' && !!window.localStorage;
var _getKey = function(key) {
return 'F2-' + key;
};
return {
/**
* @method getItem
* @param {string} key The key of the item to retrieve
*/
getItem:function(key) {
var value = null;
if (!key) { return; }
key = _getKey(key);
if (_hasLocalStorage) {
value = localStorage.getItem(key);
} else {
var cookies = document.cookie.split(/\s*;\s*/);
for (var i = 0, len = cookies.length; i < len; i++) {
var parts = cookies[i].split(/\s*=\s*/);
if (parts.length > 1 && unescape(parts[0]) == key) {
value = unescape(parts[1]);
}
}
}
if (!!value) {
value = F2.parse(value);
}
return value;
},
/**
* @method removeItem
* @param {string} key The key of the item to remove
*/
removeItem:function(key) {
if (!key) { return; }
key = _getKey(key);
if (_hasLocalStorage) {
localStorage.removeItem(key);
} else {
document.cookie = escape(key) + '=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/';
}
},
/**
* @method setItem
* @param {string} key The key of the item to set
* @param {object} value The value to be stored
*/
setItem:function(key, value) {
if (!key || !value) { return; }
key = _getKey(key);
value = F2.stringify(value);
if (_hasLocalStorage) {
localStorage.setItem(key, value);
} else {
var exp = new Date();
exp.setFullYear((new Date()).getFullYear() + 100);
document.cookie = escape(key) + '=' + escape(value) + '; expires=' + exp.toUTCString() + '; path=/';
}
}
};
})());