Permalink
Browse files

Allow adapter to implement async_each

  • Loading branch information...
1 parent 1d9df4a commit a99108a29358c66d8a4ceb725eef678c7ad93e55 @krestenkrab committed Dec 14, 2011
Showing with 40 additions and 7 deletions.
  1. +15 −5 src/Lawnchair.js
  2. +24 −1 src/adapters/indexed-db.js
  3. +1 −1 test/lawnchair-spec.js
View
20 src/Lawnchair.js
@@ -76,7 +76,10 @@ Lawnchair.adapter = function (id, obj) {
, indexOf = this.prototype.indexOf
// mix in the adapter
for (var i in obj) {
- if (indexOf(implementing, i) === -1) throw 'Invalid adapter! Nonstandard method: ' + i
+ if (indexOf(implementing, i) === -1) {
+ if (i != 'async_each')
+ throw 'Invalid adapter '+id+'! Nonstandard method: ' + i
+ }
}
// if we made it this far the adapter interface is valid
Lawnchair.adapters.push(obj)
@@ -133,17 +136,24 @@ Lawnchair.prototype = {
},
// a classic iterator
- each: function (callback) {
+ each: function (callback, done_callback) {
var cb = this.lambda(callback)
+ var cb2 = this.lambda(done_callback)
// iterate from chain
if (this.__results) {
for (var i = 0, l = this.__results.length; i < l; i++) cb.call(this, this.__results[i], i)
+ if (cb2) cb2.call(this, null, -1);
}
// otherwise iterate the entire collection
else {
- this.all(function(r) {
- for (var i = 0, l = r.length; i < l; i++) cb.call(this, r[i], i)
- })
+ if (this.async_each) {
+ this.async_each(cb, cb2);
+ } else {
+ this.all(function(r) {
+ for (var i = 0, l = r.length; i < l; i++) cb.call(this, r[i], i);
+ if (cb2) cb2.call(this, null, -1);
+ })
+ }
}
return this
}
View
25 src/adapters/indexed-db.js
@@ -154,9 +154,32 @@ Lawnchair.adapter('indexed-db', (function(){
return this;
},
- all:function(callback) {
+ async_each: function (callback, done_callback) {
if(!this.store) {
this.waiting.push(function() {
+ this.async_each(callback, done_callback);
+ });
+ return;
+ }
+ var self = this;
+ var objectStore = this.db.transaction("teststore").objectStore("teststore");
+ var index = 0;
+ objectStore.openCursor().onsuccess = function(event) {
+ var cursor = event.target.result;
+ if (cursor) {
+ if (callback) callback.call(self, cursor.value, index++);
+ cursor['continue']();
+ }
+ else {
+ if (done_callback) done_callback.call(self, null, -1);
+ }
+ };
+ return this;
+ },
+
+ all:function(callback) {
+ if(!this.store) {
+ this.waiting.push(function() {
this.all(callback);
});
return;
View
2 test/lawnchair-spec.js
@@ -109,7 +109,7 @@ test('scoped variable in shorthand callback', function() {
var tmp = new Lawnchair({name:'temps', record:'tmp'}, function() {
this.nuke(function() {
this.save({a:1}, function() {
- this.each('ok(tmp, "this.record is passed to each callback"); QUnit.start()')
+ this.each('ok(tmp, "this.record is passed to each callback");', 'QUnit.start()')
})
})
})

0 comments on commit a99108a

Please sign in to comment.