forked from joaohcrangel/jquery-jrangel-plugins
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjquery.store.js
145 lines (91 loc) · 2.51 KB
/
jquery.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
/**
*
* @name store
* @version 0.1
* @requires jQuery v1.7+
* @author João Rangel
* @license MIT License - http://www.opensource.org/licenses/mit-license.php
*
* For usage and examples, buy TopSundue:
*
*/
$.store = (function(){
return function(options){
return new (function(options){
var tryRest = 0;
var t = this, defaults = {
debug:false,
keyStorage:'sessionStore',
cache:true,
url:'',
data:{},
success:function(){},
failure:function(){}
};
var o = $.extend(defaults, options);
if (!typeof sessionStorage === 'object') console.warn('O navegador não suporte sessionStorage.');
t.clear = function(keys) {
var store = t.getStorage();
if (typeof keys === 'string') keys = keys.split(",");
$.each(keys, function(index, key){
if (store[key]) {
store[key] = [];
delete store[key];
}
});
return t.setStorage(store);
};
t.clearAll = function() {
return t.setStorage({});
};
t.setItem = function(key, data) {
var store = t.getStorage();
store[key] = data;
return t.setStorage(store);
};
t.setStorage = function(data) {
return sessionStorage.setItem(o.keyStorage, JSON.stringify(data));
};
t.getStorage = function() {
var storage = sessionStorage.getItem(o.keyStorage);
var data = {};
if (!storage) storage = '{}';
try {
data = $.parseJSON(storage);
} catch(e) {
t.setStorage({});
}
return data;
};
t.getItem = function(key) {
var data = t.getStorage();
if (o.debug === true) console.log('data', data);
if (o.debug === true) console.log('data[key]', key, data[key]);
if (o.cache === true && data[key]) {
if (o.debug === true) console.log('cache OK');
if (typeof o.success === 'function') o.success(data[key]);
} else {
if (o.debug === true) console.log('Loading...');
if (tryRest >= 3) {
console.error('Não foi possível carregar o store após '+tryRest+' tentativas.');
return true;
}
tryRest++;
rest($.extend({}, o, {
success:function(r){
if (o.debug === true) console.log('store rest success', r);
o.cache = true;
t.setItem(key, r.data);
t.getItem(key);
},
failure:function(r){
if (o.debug === true) console.log('store rest error', r);
if (typeof o.failure === 'function') o.failure(r.error || "A chave "+key+" não existe.");
}
}));
}
};
t.getItem(o.url);
})(options);
};
})();