PageRenderTime 84ms CodeModel.GetById 38ms RepoModel.GetById 0ms app.codeStats 0ms

/examples/backbone-localstorage.js

https://bitbucket.org/dlisboa/backbone
JavaScript | 136 lines | 85 code | 24 blank | 27 comment | 15 complexity | 53de93f852bf76bf5a00fcf13a24b11d MD5 | raw file
  1. /**
  2. * Backbone localStorage Adapter
  3. * https://github.com/jeromegn/Backbone.localStorage
  4. */
  5. (function() {
  6. // A simple module to replace `Backbone.sync` with *localStorage*-based
  7. // persistence. Models are given GUIDS, and saved into a JSON object. Simple
  8. // as that.
  9. // Hold reference to Underscore.js and Backbone.js in the closure in order
  10. // to make things work even if they are removed from the global namespace
  11. var _ = this._;
  12. var Backbone = this.Backbone;
  13. // Generate four random hex digits.
  14. function S4() {
  15. return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
  16. };
  17. // Generate a pseudo-GUID by concatenating random hexadecimal.
  18. function guid() {
  19. return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
  20. };
  21. // Our Store is represented by a single JS object in *localStorage*. Create it
  22. // with a meaningful name, like the name you'd give a table.
  23. // window.Store is deprectated, use Backbone.LocalStorage instead
  24. Backbone.LocalStorage = window.Store = function(name) {
  25. this.name = name;
  26. var store = this.localStorage().getItem(this.name);
  27. this.records = (store && store.split(",")) || [];
  28. };
  29. _.extend(Backbone.LocalStorage.prototype, {
  30. // Save the current state of the **Store** to *localStorage*.
  31. save: function() {
  32. this.localStorage().setItem(this.name, this.records.join(","));
  33. },
  34. // Add a model, giving it a (hopefully)-unique GUID, if it doesn't already
  35. // have an id of it's own.
  36. create: function(model) {
  37. if (!model.id) {
  38. model.id = guid();
  39. model.set(model.idAttribute, model.id);
  40. }
  41. this.localStorage().setItem(this.name+"-"+model.id, JSON.stringify(model));
  42. this.records.push(model.id.toString());
  43. this.save();
  44. return model.toJSON();
  45. },
  46. // Update a model by replacing its copy in `this.data`.
  47. update: function(model) {
  48. this.localStorage().setItem(this.name+"-"+model.id, JSON.stringify(model));
  49. if (!_.include(this.records, model.id.toString())) this.records.push(model.id.toString()); this.save();
  50. return model.toJSON();
  51. },
  52. // Retrieve a model from `this.data` by id.
  53. find: function(model) {
  54. return JSON.parse(this.localStorage().getItem(this.name+"-"+model.id));
  55. },
  56. // Return the array of all models currently in storage.
  57. findAll: function() {
  58. return _(this.records).chain()
  59. .map(function(id){return JSON.parse(this.localStorage().getItem(this.name+"-"+id));}, this)
  60. .compact()
  61. .value();
  62. },
  63. // Delete a model from `this.data`, returning it.
  64. destroy: function(model) {
  65. this.localStorage().removeItem(this.name+"-"+model.id);
  66. this.records = _.reject(this.records, function(record_id){return record_id == model.id.toString();});
  67. this.save();
  68. return model;
  69. },
  70. localStorage: function() {
  71. return localStorage;
  72. }
  73. });
  74. // localSync delegate to the model or collection's
  75. // *localStorage* property, which should be an instance of `Store`.
  76. // window.Store.sync and Backbone.localSync is deprectated, use Backbone.LocalStorage.sync instead
  77. Backbone.LocalStorage.sync = window.Store.sync = Backbone.localSync = function(method, model, options, error) {
  78. var store = model.localStorage || model.collection.localStorage;
  79. // Backwards compatibility with Backbone <= 0.3.3
  80. if (typeof options == 'function') {
  81. options = {
  82. success: options,
  83. error: error
  84. };
  85. }
  86. var resp;
  87. switch (method) {
  88. case "read": resp = model.id != undefined ? store.find(model) : store.findAll(); break;
  89. case "create": resp = store.create(model); break;
  90. case "update": resp = store.update(model); break;
  91. case "delete": resp = store.destroy(model); break;
  92. }
  93. if (resp) {
  94. options.success(model, resp, options);
  95. } else {
  96. options.error(model, "Record not found", options);
  97. }
  98. };
  99. Backbone.ajaxSync = Backbone.sync;
  100. Backbone.getSyncMethod = function(model) {
  101. if(model.localStorage || (model.collection && model.collection.localStorage))
  102. {
  103. return Backbone.localSync;
  104. }
  105. return Backbone.ajaxSync;
  106. };
  107. // Override 'Backbone.sync' to default to localSync,
  108. // the original 'Backbone.sync' is still available in 'Backbone.ajaxSync'
  109. Backbone.sync = function(method, model, options, error) {
  110. return Backbone.getSyncMethod(model).apply(this, [method, model, options, error]);
  111. };
  112. })();