Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // 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),
- };
- }
- },
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement