Skip to content

Instantly share code, notes, and snippets.

@joews
Created August 15, 2014 09:24
Show Gist options
  • Save joews/ba11edf04529c4603323 to your computer and use it in GitHub Desktop.
Save joews/ba11edf04529c4603323 to your computer and use it in GitHub Desktop.
Make Backbone Collections and Models aware of their current sync state
// Patch Backbone Model and Collection to have awareness
// of current sync state.
// Adds an isLoading method and _inFlight count property.
// Fires before:sync and after:sync events.
// Based on http://tbranyen.com/post/how-to-indicate-backbone-fetch-progress
!function() {
function onSyncEnd() {
-- this._inFlight;
this.trigger("after:sync", this);
}
_.each([Backbone.Model, Backbone.Collection], function(Type) {
var originalSync = Type.prototype.sync;
Type.prototype._inFlight = 0;
Type.prototype.isLoading = function() {
return this._inFlight > 0;
}
Type.prototype.sync = function() {
var synced = onSyncEnd.bind(this);
this.trigger("before:sync", this);
++ this._inFlight;
return originalSync.apply(this, arguments)
.then(synced, synced);
};
});
}();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment