Skip to content

Instantly share code, notes, and snippets.

@brandonhall
Last active May 1, 2016 06:10
Show Gist options
  • Save brandonhall/4720002 to your computer and use it in GitHub Desktop.
Save brandonhall/4720002 to your computer and use it in GitHub Desktop.
An example of overriding Backbone.sync and Backbone.parse to load data from localStorage in Backbone
// 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),
};
}
},
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment