-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpersistentArray.js
124 lines (100 loc) · 2.46 KB
/
persistentArray.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
/**
* Persistent array class for google chrome extensions
*
* @author DraCzris <[email protected]>
*/
;(function(){
var Def = function(){ return constructor.apply(this,arguments); }
var attr = Def.prototype;
// list the attributes
attr.namespace;
attr.data = [];
// event functions
attr.loading = function(){console.log("loading")};
attr.loaded = function(){console.log("loaded")};
attr.saved = function(){console.log("saved")};
/**
* Constructor of persistable array
* @param {string} namespace Unique array namespace
* @param {object} callbacks Callback functions for event reaction
*/
function constructor(namespace, callbacks) {
this.namespace = 'persistArray_' + namespace;
if (typeof callbacks !== 'undefined') {
this.loading = typeof callbacks.loading !== 'undefined' ? callbacks.loading : attr.loading;
this.loaded = typeof callbacks.loaded !== 'undefined' ? callbacks.loaded : attr.loaded;
this.saved = typeof callbacks.saved !== 'undefined' ? callbacks.saved : attr.saved;
}
this.data = [];
this._load();
}
/**
* BASIC ARRAY MANIPULATION
*/
attr.get = function(index) {
return this.data[index];
}
attr.getAll = function() {
return this.data;
}
attr.size = function() {
return this.data.length;
}
attr.add = function(item) {
this.data.push(item);
this._persist();
}
attr.remove = function(index) {
this.data.splice(index, 1);
this._persist();
}
/**
* CORE
*/
/**
* Set data of array
* @param {Array} array Array of items
*/
attr._setData = function(array) {
this.data = array;
}
/**
* Getter on data
* @return {Array} Array of items
*/
attr._getData = function() {
return this.data;
}
/**
* Load array from storage
*/
attr._load = function() {
this.loading();
var that = this;
chrome.storage.sync.get(this.namespace, function(persistObject) {
if (typeof persistObject[that.namespace] === 'undefined') {
that._setData(new Array());
} else {
that._setData(persistObject[that.namespace]);
}
that.loaded();
});
}
/**
* Persists array to storage
* @return {[type]} [description]
*/
attr._persist = function() {
this.loading();
var that = this;
var payload = {};
payload[this.namespace] = this.data;
chrome.storage.sync.set(payload, function() {
that.saved();
});
}
attr._clear = function() {
chrome.storage.sync.clear(function(){alert("Cleared");});
}
window.PersistentArray = Def;
})();