Skip to content

Instantly share code, notes, and snippets.

@ruudud
Created December 4, 2013 13:30
Show Gist options
  • Save ruudud/7787422 to your computer and use it in GitHub Desktop.
Save ruudud/7787422 to your computer and use it in GitHub Desktop.
Queued save in Backbone.Model using jQuery Deferred
var QueuedModel = Backbone.Model.extend({
url: function () {
var delay = Math.floor(Math.random() * 7);
return "/echo/json/?delay=" + delay;
},
initialize : function () {
this.saveQueue = jQuery.Deferred();
this.saveQueue.resolve();
this.on("sync", function () {
console.log("sync");
});
},
save: function (attrs, options) {
var model = this;
console.log("set " + JSON.stringify(attrs));
this.saveQueue = this.saveQueue.then(function () {
console.log("request " + JSON.stringify(attrs));
return Backbone.Model.prototype.save.call(model, attrs, options);
});
}
});
var m = new QueuedModel();
m.save({ title: "1. a title" });
m.save({ description: "2. a description" });
m.save({ title: "3. a new title" });
m.save({ price: "4. a price" });
@ruudud
Copy link
Author

ruudud commented Dec 4, 2013

Requires jQuery >= v1.8. If using 1.7, replace then() with pipe().

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment