Advertisement
Guest User

Untitled

a guest
May 1st, 2016
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.16 KB | None | 0 0
  1. // Overriding Backbone.sync to either load locally or from the server
  2. sync: function(method, model, options) {
  3.  
  4. // Pull the key and stored object localStorage
  5. var storageKey = localStorage.getItem('storage');
  6. var storageData = localStorage.getItem('storage-' + storageKey);
  7.  
  8. // Apply the callback with our local data
  9. if(storageData) {
  10. options.success(JSON.parse(storageData));
  11. }
  12. // No local data so run .getJSON to fetch it from the server
  13. else {
  14. $.getJSON(this.url, function(data, textStatus) {
  15. if(textStatus !== 'success' || !data) {
  16. options.error();
  17. }
  18. options.success(data);
  19. });
  20. }
  21. }
  22.  
  23. // Overriding Backbone.parse to fill models from local data
  24. parse: function(response) {
  25. // Loading from localStorage so we intercept to properly
  26. // serialize the object in our Backbone.collections
  27. var self = this;
  28.  
  29. // In my case, the object loaded from storage was an array
  30. // Backbone usually passes an object to parse
  31. if(response.length) {
  32.  
  33. // Set properties on our model and return it
  34. return {
  35. id: response.id,
  36. myCollection: self.collection.add(response.myCollection),
  37. };
  38. }
  39. },
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement