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