Skip to content

Instantly share code, notes, and snippets.

@suprememoocow
Created May 21, 2013 17:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save suprememoocow/5621667 to your computer and use it in GitHub Desktop.
Save suprememoocow/5621667 to your computer and use it in GitHub Desktop.
var LiveCollection = Backbone.Collection.extend({
...
_createEvent: function(body) {
...
// Look to see if this collection has any outstanding creates...
var idAttribute = this.model.prototype.idAttribute;
var unsaved = this.filter(function(model) {
return !model.id;
});
// If there are unsaved items, monitor them and if one of them turns out to be the matching object
// then simply update that
if(unsaved.length) {
console.log('live: awaiting syncs of unsaved objects');
var listener = new UpdateEventListener(id, unsaved);
listener.once('notfound', function() {
this.add(body, { parse: true });
}, this);
} else {
this.add(body, { parse: true });
}
}
...
});
function UpdateEventListener(outstandingId, models) {
this._outstandingId = outstandingId;
this._awaitCount = models.length;
_.each(models, function(model) {
this.listenToOnce(model, 'sync error', this._onModelSync);
}, this);
}
_.extend(UpdateEventListener.prototype, Backbone.Events, {
_onModelSync: function(model) {
if(model.id === this._outstandingId) {
// Great, this is the model we're waiting for!
this.trigger('found', model);
this.stopListening();
} else if(--this._awaitCount === 0) {
// All the models are done and we haven't found the id we received from the realtime stream
this.stopListening();
this.trigger('notfound');
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment