Last active
December 10, 2015 18:34
-
-
Save philfreo/fc068094f6e26d6995e2 to your computer and use it in GitHub Desktop.
Backbone.js patch to prevent duplicate POSTs
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 | |
// http://stackoverflow.com/a/6122530/137067 | |
// https://gist.github.com/1037984 | |
Backbone.Model.prototype._save = Backbone.Model.prototype.save; | |
Backbone.Model.prototype.save = function(attrs, options) { | |
// Queue up consecutive requests if the model is new and the initial | |
// POST request hasn't finished yet (xhr.readyState === 4 if the | |
// "request finished and response is ready"). | |
if (this.isNew() && this.request && this.request.readyState !== 4) { | |
var dit = this, args = arguments; | |
// Passing an empty attrs value means that the model's current attributes should be persisted. | |
// However in this case we're actually waiting until the previous POST has completed. | |
// So we need to explicitly keep track of the attributes at the time of the original call, | |
// or else by the time the promise callback completes, we might be trying to save some newly | |
// changed attributes (from the POST) which would make us lose our desired attributes from the 2nd save. | |
if (_.isEmpty(attrs)) attrs = this.toJSON(); | |
$.when(this.request).always(function() { | |
Backbone.Model.prototype._save.apply(dit, args); | |
}); | |
} else { | |
this.request = Backbone.Model.prototype._save.apply(this, arguments); | |
return this.request; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment