Skip to content

Instantly share code, notes, and snippets.

@philfreo
Forked from mattheworiordan/gist:1037984
Created July 20, 2012 01:21
Show Gist options
  • Save philfreo/3148064 to your computer and use it in GitHub Desktop.
Save philfreo/3148064 to your computer and use it in GitHub Desktop.
Backbone patch to defer update method requests when new create requests are not complete on a model
// Queue of Backbone.Model save()s so that we don't issue multiple POSTs while waiting for
// the first one to come back. The first save() will always POST and the second will always PUT now.
// https://github.com/documentcloud/backbone/issues/345
// https://gist.github.com/1037984 and https://gist.github.com/gists/3148064
(function() {
function proxyAjaxEvent(event, options, dit) {
var eventCallback = options[event];
options[event] = function() {
// check if callback for event exists and if so pass on request
if (eventCallback) { eventCallback(arguments) }
dit.processQueue(); // move onto next save request in the queue
}
}
Backbone.Model.prototype._save = Backbone.Model.prototype.save;
Backbone.Model.prototype.save = function( attrs, options ) {
if (!options) { options = {}; }
if (this.saving) {
this.saveQueue = this.saveQueue || new Array();
this.saveQueue.push({ attrs: _.extend({}, this.attributes, attrs), options: options });
} else {
this.saving = true;
proxyAjaxEvent('success', options, this);
proxyAjaxEvent('error', options, this);
Backbone.Model.prototype._save.call( this, attrs, options );
}
}
Backbone.Model.prototype.processQueue = function() {
if (this.saveQueue && this.saveQueue.length) {
var saveArgs = this.saveQueue.shift();
proxyAjaxEvent('success', saveArgs.options, this);
proxyAjaxEvent('error', saveArgs.options, this);
Backbone.Model.prototype._save.call( this, saveArgs.attrs, saveArgs.options );
} else {
this.saving = false;
}
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment