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/3148065 to your computer and use it in GitHub Desktop.
Save philfreo/3148065 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
(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) }
if (eventCallback) { eventCallback.apply(dit, arguments); }
dit.proxyProcessQueue(); // 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.isNew() && this.saving) {
this.saveQueue = this.saveQueue || [];
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.proxyProcessQueue = 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