forked from brianleroux/lawnchair
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathLawnchair.js
75 lines (62 loc) · 2.06 KB
/
Lawnchair.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
/**
* Lawnchair
* =========
* A lightweight JSON document store.
*
*/
var Lawnchair = function(opts) {
this.init(opts);
}
Lawnchair.prototype = {
init:function(opts) {
var adaptors = {
'webkit':window.WebkitSQLiteAdaptor,
'gears':window.GearsSQLiteAdaptor,
'dom':window.DOMStorageAdaptor,
'cookie':window.CookieAdaptor,
'air':window.AIRSQLiteAdaptor
};
this.adaptor = opts.adaptor ? new adaptors[opts.adaptor](opts) : new WebkitSQLiteAdaptor(opts);
},
// Save an object to the store. If a key is present then update. Otherwise create a new record.
save:function(obj, callback) {this.adaptor.save(obj, callback)},
// Invokes a callback on an object with the matching key.
get:function(key, callback) {this.adaptor.get(key, callback)},
// Returns whether a key exists to a callback.
exists:function(callback) {this.adaptor.exists(callback)},
// Returns all rows to a callback.
all:function(callback) {this.adaptor.all(callback)},
// Removes a json object from the store.
remove:function(keyOrObj, callback) {this.adaptor.remove(keyOrObj, callback)},
// Removes all documents from a store and returns self.
nuke:function(callback) {this.adaptor.nuke(callback);return this},
/**
* Iterator that accepts two paramters (methods or eval strings):
*
* - conditional test for a record
* - callback to invoke on matches
*
*/
find:function(condition, callback) {
var is = (typeof condition == 'string') ? function(r){return eval(condition)} : condition;
var cb = this.adaptor.terseToVerboseCallback(callback);
this.each(function(record, index) {
if (is(record)) cb(record, index); // thats hot
});
},
/**
* Classic iterator.
* - Passes the record and the index as the second parameter to the callback.
* - Accepts a string for eval or a method to be invoked for each document in the collection.
*/
each:function(callback) {
var cb = this.adaptor.terseToVerboseCallback(callback);
this.all(function(results) {
var l = results.length;
for (var i = 0; i < l; i++) {
cb(results[i], i);
}
});
}
// --
};