Created
August 15, 2014 09:24
-
-
Save joews/ba11edf04529c4603323 to your computer and use it in GitHub Desktop.
Make Backbone Collections and Models aware of their current sync state
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
// 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