-
-
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
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
// 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