This repository has been archived by the owner on Nov 28, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.js
82 lines (65 loc) · 1.58 KB
/
db.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
var Db = (function(){
var C = function(){ return constructor.apply(this,arguments); }
var p = C.prototype;
p.notes;
p._loadedCallbacks = [];
p._updatedCallbacks = [];
function constructor(){
this.dbName = 'ReviewsOnGitHub';
this.notes = [];
}
p.loaded = function (fn) {
this._loadedCallbacks.push(fn)
}
p.updated = function (fn) {
this._updatedCallbacks.push(fn)
}
p.loadedOrUpated = function (fn) {
this.updated(fn);
this.loaded(fn);
}
p.find = function (url) {
return this.notes.filter(function (note) {
return note.url == url;
});
}
p.remove = function (url) {
var note = this.find(url)[0];
var index = this.notes.indexOf(note);
if (index > -1) {
this.notes.splice(index, 1);
}
this.save();
}
p.add = function (url, body, options) {
this.notes.push ({
"url": url,
"body": body,
"options": options
})
}
p.addOrUpdate = function (url, body, options) {
var existingNote = this.find(url)[0];
if (existingNote) {
this.remove(url);
}
this.add(url, body, options);
}
p.save = function (fn) {
localStorage.setItem(this.dbName, JSON.stringify(this.notes));
for (var i = 0; i < this._updatedCallbacks.length; i++) {
this._updatedCallbacks[i]();
}
if (fn)
fn();
}
p.load = function () {
this.notes = JSON.parse(localStorage.getItem(this.dbName));
if (!this.notes)
this.notes = [];
for (var i = 0; i < this._loadedCallbacks.length; i++) {
this._loadedCallbacks[i]();
}
}
return C;
})();