Guest User

Untitled

a guest
Feb 18th, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.42 KB | None | 0 0
  1. // Generate four random hex digits.
  2. function S4() {
  3. return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
  4. };
  5.  
  6. // Generate a pseudo-GUID by concatenating random hexadecimal.
  7. function guid() {
  8. return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
  9. };
  10.  
  11. // Our Store is represented by a single JS object in *localStorage*. Create it
  12. // with a meaningful name, like the name you'd give a table.
  13. var Store = function(name) {
  14. this.name = name;
  15. var store = localStorage.getItem(this.name);
  16. this.data = (store && JSON.parse(store)) || {};
  17. };
  18.  
  19. _.extend(Store.prototype, {
  20.  
  21. // Save the current state of the **Store** to *localStorage*.
  22. save: function() {
  23. localStorage.setItem(this.name, JSON.stringify(this.data));
  24. },
  25.  
  26. // Add a model, giving it a (hopefully)-unique GUID, if it doesn't already
  27. // have an id of it's own.
  28. create: function(model) {
  29. if (!model.id) model.id = model.attributes.id = guid();
  30. this.data[model.id] = model;
  31. this.save();
  32. return model;
  33. },
  34.  
  35. // Update a model by replacing its copy in `this.data`.
  36. update: function(model) {
  37. this.data[model.id] = model;
  38. this.save();
  39. return model;
  40. },
  41.  
  42. // Retrieve a model from `this.data` by id.
  43. find: function(model) {
  44. return this.data[model.id];
  45. },
  46.  
  47. // Return the array of all models currently in storage.
  48. findAll: function() {
  49. return _.values(this.data);
  50. },
  51.  
  52. // Delete a model from `this.data`, returning it.
  53. destroy: function(model) {
  54. delete this.data[model.id];
  55. this.save();
  56. return model;
  57. }
  58.  
  59. });
  60.  
  61. // Override `Backbone.sync` to use delegate to the model or collection's
  62. // *localStorage* property, which should be an instance of `Store`.
  63. var $super = Backbone.sync;
  64. if ('localStorage' in window) {
  65. Backbone.sync = function(method, model, options) {
  66. var resp, store = model.localStorage || (model.collection && model.collection.localStorage);
  67. if (typeof store === 'undefined') return $super(method, model, options);
  68.  
  69. switch (method) {
  70. case "read": resp = model.id ? store.find(model) : store.findAll(); break;
  71. case "create": resp = store.create(model); break;
  72. case "update": resp = store.update(model); break;
  73. case "delete": resp = store.destroy(model); break;
  74. }
  75. if (resp) {
  76. options.success(resp);
  77. } else {
  78. options.error("Record not found");
  79. }
  80. };
  81. }
Add Comment
Please, Sign In to add comment