public
Last active

An example of overriding Backbone.sync and Backbone.parse to load data from localStorage in Backbone

  • Download Gist
localStorage.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
// Overriding Backbone.sync to either load locally or from the server
sync: function(method, model, options) {
// Pull the key and stored object localStorage
var storageKey = localStorage.getItem('storage');
var storageData = localStorage.getItem('storage-' + storageKey);
 
// Apply the callback with our local data
if(storageData) {
options.success(JSON.parse(storageData));
}
// No local data so run .getJSON to fetch it from the server
else {
$.getJSON(this.url, function(data, textStatus) {
if(textStatus !== 'success' || !data) {
options.error();
}
options.success(data);
});
}
}
 
// Overriding Backbone.parse to fill models from local data
parse: function(response) {
// Loading from localStorage so we intercept to properly
// serialize the object in our Backbone.collections
var self = this;
// In my case, the object loaded from storage was an array
// Backbone usually passes an object to parse
if(response.length) {
// Set properties on our model and return it
return {
id: response.id,
myCollection: self.collection.add(response.myCollection),
};
}
},
 

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.