Skip to content

Instantly share code, notes, and snippets.

@geon
Created December 10, 2013 13:05
Show Gist options
  • Save geon/7890291 to your computer and use it in GitHub Desktop.
Save geon/7890291 to your computer and use it in GitHub Desktop.
Experimenting with a LocalStorage buffer for backbone in case of dropped connection.
"use strict";
var LocalBuffered = {};
LocalBuffered.Model = Backbone.Model.extend({
constructor: function () {
Backbone.Model.apply(this, arguments);
this.on("error", function(model){
model.saveLocal();
});
this.on("sync", function(model){
model.clearLocal();
});
},
saveLocal: function () {
// The data to save.
var data = this.toJSON();
// Read all local objects.
var locals = JSON.parse(localStorage[this.collection.url] || "[]");
// Find the local version of this object if it was already saved.
var search = {}
search[this.idAttribute] = this.id;
var local = _.findWhere(locals, search);
if (local) {
// Update the existing local object.
_.extend(local, data);
} else {
// Add the object to the local ones.
locals.push(data)
}
// Save everything back.
localStorage[this.collection.url] = JSON.stringify(locals);
},
clearLocal: function () {
// Read all local objects.
var locals = JSON.parse(localStorage[this.collection.url] || "[]");
// Find the local version of this object if it was already saved.
var search = {}
search[this.idAttribute] = this.id;
var local = _.findWhere(locals, search);
if (local) {
// Remove it.
locals.splice(locals.indexOf(local), 1);
}
// Save everything back.
localStorage[this.collection.url] = JSON.stringify(locals);
}
});
LocalBuffered.Collection = Backbone.Collection.extend({
fetch: function () {
// Do the fetch as normal...
var self = this;
return Backbone.Collection.prototype.fetch.apply(this, arguments).then(function(){
///...But merge in the local objects.
self.addLocal();
});
},
addLocal: function () {
// Read all local objects.
var locals = JSON.parse(localStorage[this.url] || "[]");
_.each(locals, function(local){
// Create a proper Backbone model from the data.
var model = new this.model(local);
// Add it to this collection, overwriting any existing version.
this.add(model, {merge: true});
// Send the data to the server.
model.save();
}, this);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment