Created
May 21, 2013 17:36
-
-
Save suprememoocow/5621667 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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