diff --git a/lib/live-collection.js b/lib/live-collection.js index f08e8ee..0330d1a 100644 --- a/lib/live-collection.js +++ b/lib/live-collection.js @@ -1,5 +1,7 @@ "use strict"; +var Halley = require('halley/backbone'); +var Promise = Halley.Promise; var _ = require('underscore'); var Backbone = require('backbone'); var backboneUrlResolver = require('backbone-url-resolver'); @@ -27,6 +29,9 @@ module.exports = Backbone.Collection.extend({ var defaults = { snapshot: true }; options = _.extend(defaults, options); + // indicates if this LiveCollection has received at least one snapshot ever + this._snapshotReceived = false; + if (options.client) { this.client = options.client; } else { @@ -158,6 +163,8 @@ module.exports = Backbone.Collection.extend({ }, _resetOptional: function() { + this._snapshotReceived = false; + if (!this.length) return; // Performance tweak @@ -191,10 +198,33 @@ module.exports = Backbone.Collection.extend({ this.reset(snapshot, options); } + this._snapshotReceived = true; + this.trigger('sync'); this.trigger('snapshot'); }, + onSnapshotReceived: function() { + var self = this; + if (this._snapshotReceived) { + debug('Snapshot already received, resolving immediately'); + return Promise.resolve(); + } else { + debug('Awaiting snapshot'); + return new Promise(function(resolve, reject) { + self.once('snapshot', function() { + var resolved = true; + debug('Snapshot received'); + resolve(); + }); + self.once('error', function(err) { + debug('Error received before promise could get resolved.'); + reject(err); + }); + }); + } + }, + findExistingModel: function(id, newModel) { var existing = this.get(id); if(existing) return existing;