PageRenderTime 56ms CodeModel.GetById 27ms RepoModel.GetById 1ms app.codeStats 0ms

/static/backbone/examples/backbone-localstorage.js

https://github.com/weblancer23/Final-Project
JavaScript | 85 lines | 54 code | 15 blank | 16 comment | 7 complexity | d81de255e73d4812fe9e238fdcd77621 MD5 | raw file
  1. // A simple module to replace `Backbone.sync` with *localStorage*-based
  2. // persistence. Models are given GUIDS, and saved into a JSON object. Simple
  3. // as that.
  4. // Generate four random hex digits.
  5. function S4() {
  6. return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
  7. };
  8. // Generate a pseudo-GUID by concatenating random hexadecimal.
  9. function guid() {
  10. return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
  11. };
  12. // Our Store is represented by a single JS object in *localStorage*. Create it
  13. // with a meaningful name, like the name you'd give a table.
  14. var Store = function(name) {
  15. this.name = name;
  16. var store = localStorage.getItem(this.name);
  17. this.data = (store && JSON.parse(store)) || {};
  18. };
  19. _.extend(Store.prototype, {
  20. // Save the current state of the **Store** to *localStorage*.
  21. save: function() {
  22. localStorage.setItem(this.name, JSON.stringify(this.data));
  23. },
  24. // Add a model, giving it a (hopefully)-unique GUID, if it doesn't already
  25. // have an id of it's own.
  26. create: function(model) {
  27. if (!model.id) model.id = model.attributes.id = guid();
  28. this.data[model.id] = model;
  29. this.save();
  30. return model;
  31. },
  32. // Update a model by replacing its copy in `this.data`.
  33. update: function(model) {
  34. this.data[model.id] = model;
  35. this.save();
  36. return model;
  37. },
  38. // Retrieve a model from `this.data` by id.
  39. find: function(model) {
  40. return this.data[model.id];
  41. },
  42. // Return the array of all models currently in storage.
  43. findAll: function() {
  44. return _.values(this.data);
  45. },
  46. // Delete a model from `this.data`, returning it.
  47. destroy: function(model) {
  48. delete this.data[model.id];
  49. this.save();
  50. return model;
  51. }
  52. });
  53. // Override `Backbone.sync` to use delegate to the model or collection's
  54. // *localStorage* property, which should be an instance of `Store`.
  55. Backbone.sync = function(method, model, options) {
  56. var resp;
  57. var store = model.localStorage || model.collection.localStorage;
  58. switch (method) {
  59. case "read": resp = model.id ? store.find(model) : store.findAll(); break;
  60. case "create": resp = store.create(model);console
  61. break;
  62. case "update": resp = store.update(model); break;
  63. case "delete": resp = store.destroy(model); break;
  64. }
  65. if (resp) {
  66. options.success(resp);
  67. } else {
  68. options.error("Record not found");
  69. }
  70. };