-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
143 lines (108 loc) · 2.78 KB
/
index.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
var _ = require('underscore');
/**
The LocalStore singleton.
@class TemplateStore
@constructor
**/
var LocalStore = module.exports = {
/**
This object stores all keys and their values.
@property keys
@type Object
@default {}
@example
{
name->myProperty: "myValue",
...
}
**/
keys: {},
/**
Keeps the dependencies for the keys in the store.
@property deps
@type Object
@default {}
@example
{
name->myProperty: new Tracker.Dependency,
...
}
**/
deps: {},
// METHODS
// PRIVATE
/**
Creates at least ones a `Tracker.Dependency` object to a key.
@method _ensureDeps
@private
@param {String} key the name of the key to add a dependecy tracker to
@return undefined
**/
_ensureDeps: function (key) {
if (!this.deps[key] && (typeof Tracker !== "undefined")){
this.deps[key] = new Tracker.Dependency;
}
},
set: function(key, value, options, callback){
this._ensureDeps(key);
// USE CHROME STORAGE
if(typeof chrome !== 'undefined' && chrome.storage) {
var item = {};
item[key] = value;
// set
chrome.storage.local.set(item, function(){
// re-run reactive functions
if((!options || options.reactive !== false)
&& (typeof Tracker != "undefined"))
this.deps[key].changed();
// run callbacks
if(_.isFunction(callback))
callback();
});
// USE LOCALSTORAGE
} else {
// stringify
if(_.isObject(value))
value = JSON.stringify(value);
// set
// use try to prevent warnings from low cache storages
try {
localStorage.setItem(key, value);
} catch(e) {
}
// re-run reactive functions
if((!options || options.reactive !== false)
&& (typeof Tracker !== "undefined"))
this.deps[key].changed();
// run callbacks
if(_.isFunction(callback))
callback();
}
},
get: function(key, options, callback){
this._ensureDeps(key);
// DEPEND REACTIVE FUNCTIONS
if((!options || options.reactive !== false)
&& (typeof Tracker !== "undefined"))
this.deps[key].depend();
// use chrome storage
if(typeof chrome !== 'undefined' && chrome.storage) {
// get
chrome.storage.local.get(key, callback);
// USE LOCALSTORAGE
} else {
// get
var value = localStorage.getItem(key),
retunValue = value;
// try to parse
if(value && _.isString(value)) {
try {
retunValue = JSON.parse(value);
} catch(error){
retunValue = value;
}
}
return retunValue;
}
}
}