Skip to content
This repository was archived by the owner on Feb 5, 2020. It is now read-only.

onSnapshotReceived modelled after onMongoConnect #16

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions lib/live-collection.js
Original file line number Diff line number Diff line change
@@ -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');
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -158,6 +163,8 @@ module.exports = Backbone.Collection.extend({
},

_resetOptional: function() {
this._snapshotReceived = false;

if (!this.length) return;

// Performance tweak
Expand Down Expand Up @@ -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;
Expand Down