Last active
May 1, 2016 06:10
-
-
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
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
// 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