PageRenderTime 66ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/app/vendor/backbone.localstorage/backbone.localStorage.js

https://github.com/corsairdnb/vuaro
JavaScript | 249 lines | 174 code | 37 blank | 38 comment | 49 complexity | aa5c8e18567153059d222721b9986e7a MD5 | raw file
Possible License(s): BSD-3-Clause
  1. /**
  2. * Backbone localStorage Adapter
  3. * Version 1.1.9
  4. *
  5. * https://github.com/jeromegn/Backbone.localStorage
  6. */
  7. (function (root, factory) {
  8. if (typeof exports === 'object' && typeof require === 'function') {
  9. module.exports = factory(require("backbone"));
  10. } else if (typeof define === "function" && define.amd) {
  11. // AMD. Register as an anonymous module.
  12. define(["backbone"], function(Backbone) {
  13. // Use global variables if the locals are undefined.
  14. return factory(Backbone || root.Backbone);
  15. });
  16. } else {
  17. factory(Backbone);
  18. }
  19. }(this, function(Backbone) {
  20. // A simple module to replace `Backbone.sync` with *localStorage*-based
  21. // persistence. Models are given GUIDS, and saved into a JSON object. Simple
  22. // as that.
  23. // Hold reference to Underscore.js and Backbone.js in the closure in order
  24. // to make things work even if they are removed from the global namespace
  25. // Generate four random hex digits.
  26. function S4() {
  27. return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
  28. };
  29. // Generate a pseudo-GUID by concatenating random hexadecimal.
  30. function guid() {
  31. return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
  32. };
  33. function contains(array, item) {
  34. var i = array.length;
  35. while (i--) if (array[i] === item) return true;
  36. return false;
  37. }
  38. function extend(obj, props) {
  39. for (var key in props) obj[key] = props[key]
  40. return obj;
  41. }
  42. // Our Store is represented by a single JS object in *localStorage*. Create it
  43. // with a meaningful name, like the name you'd give a table.
  44. // window.Store is deprectated, use Backbone.LocalStorage instead
  45. Backbone.LocalStorage = window.Store = function(name, serializer) {
  46. if( !this.localStorage ) {
  47. throw "Backbone.localStorage: Environment does not support localStorage."
  48. }
  49. this.name = name;
  50. this.serializer = serializer || {
  51. serialize: function(item) {
  52. return _.isObject(item) ? JSON.stringify(item) : item;
  53. },
  54. // fix for "illegal access" error on Android when JSON.parse is passed null
  55. deserialize: function (data) {
  56. return data && JSON.parse(data);
  57. }
  58. };
  59. var store = this.localStorage().getItem(this.name);
  60. this.records = (store && store.split(",")) || [];
  61. };
  62. extend(Backbone.LocalStorage.prototype, {
  63. // Save the current state of the **Store** to *localStorage*.
  64. save: function() {
  65. this.localStorage().setItem(this.name, this.records.join(","));
  66. },
  67. // Add a model, giving it a (hopefully)-unique GUID, if it doesn't already
  68. // have an id of it's own.
  69. create: function(model) {
  70. if (!model.id) {
  71. model.id = guid();
  72. model.set(model.idAttribute, model.id);
  73. }
  74. this.localStorage().setItem(this._itemName(model.id), this.serializer.serialize(model));
  75. this.records.push(model.id.toString());
  76. this.save();
  77. return this.find(model) !== false;
  78. },
  79. // Update a model by replacing its copy in `this.data`.
  80. update: function(model) {
  81. this.localStorage().setItem(this._itemName(model.id), this.serializer.serialize(model));
  82. var modelId = model.id.toString();
  83. if (!contains(this.records, modelId)) {
  84. this.records.push(modelId);
  85. this.save();
  86. }
  87. return this.find(model) !== false;
  88. },
  89. // Retrieve a model from `this.data` by id.
  90. find: function(model) {
  91. return this.serializer.deserialize(this.localStorage().getItem(this._itemName(model.id)));
  92. },
  93. // Return the array of all models currently in storage.
  94. findAll: function() {
  95. var result = [];
  96. for (var i = 0, id, data; i < this.records.length; i++) {
  97. id = this.records[i];
  98. data = this.serializer.deserialize(this.localStorage().getItem(this._itemName(id)));
  99. if (data != null) result.push(data);
  100. }
  101. return result;
  102. },
  103. // Delete a model from `this.data`, returning it.
  104. destroy: function(model) {
  105. this.localStorage().removeItem(this._itemName(model.id));
  106. var modelId = model.id.toString();
  107. for (var i = 0, id; i < this.records.length; i++) {
  108. if (this.records[i] === modelId) {
  109. this.records.splice(i, 1);
  110. }
  111. }
  112. this.save();
  113. return model;
  114. },
  115. localStorage: function() {
  116. return localStorage;
  117. },
  118. // Clear localStorage for specific collection.
  119. _clear: function() {
  120. var local = this.localStorage(),
  121. itemRe = new RegExp("^" + this.name + "-");
  122. // Remove id-tracking item (e.g., "foo").
  123. local.removeItem(this.name);
  124. // Match all data items (e.g., "foo-ID") and remove.
  125. for (var k in local) {
  126. if (itemRe.test(k)) {
  127. local.removeItem(k);
  128. }
  129. }
  130. this.records.length = 0;
  131. },
  132. // Size of localStorage.
  133. _storageSize: function() {
  134. return this.localStorage().length;
  135. },
  136. _itemName: function(id) {
  137. return this.name+"-"+id;
  138. }
  139. });
  140. // localSync delegate to the model or collection's
  141. // *localStorage* property, which should be an instance of `Store`.
  142. // window.Store.sync and Backbone.localSync is deprecated, use Backbone.LocalStorage.sync instead
  143. Backbone.LocalStorage.sync = window.Store.sync = Backbone.localSync = function(method, model, options) {
  144. var store = model.localStorage || model.collection.localStorage;
  145. var resp, errorMessage;
  146. //If $ is having Deferred - use it.
  147. var syncDfd = Backbone.$ ?
  148. (Backbone.$.Deferred && Backbone.$.Deferred()) :
  149. (Backbone.Deferred && Backbone.Deferred());
  150. try {
  151. switch (method) {
  152. case "read":
  153. resp = model.id != undefined ? store.find(model) : store.findAll();
  154. break;
  155. case "create":
  156. resp = store.create(model);
  157. break;
  158. case "update":
  159. resp = store.update(model);
  160. break;
  161. case "delete":
  162. resp = store.destroy(model);
  163. break;
  164. }
  165. } catch(error) {
  166. if (error.code === 22 && store._storageSize() === 0)
  167. errorMessage = "Private browsing is unsupported";
  168. else
  169. errorMessage = error.message;
  170. }
  171. if (resp) {
  172. if (options && options.success) {
  173. if (Backbone.VERSION === "0.9.10") {
  174. options.success(model, resp, options);
  175. } else {
  176. options.success(resp);
  177. }
  178. }
  179. if (syncDfd) {
  180. syncDfd.resolve(resp);
  181. }
  182. } else {
  183. errorMessage = errorMessage ? errorMessage
  184. : "Record Not Found";
  185. if (options && options.error)
  186. if (Backbone.VERSION === "0.9.10") {
  187. options.error(model, errorMessage, options);
  188. } else {
  189. options.error(errorMessage);
  190. }
  191. if (syncDfd)
  192. syncDfd.reject(errorMessage);
  193. }
  194. // add compatibility with $.ajax
  195. // always execute callback for success and error
  196. if (options && options.complete) options.complete(resp);
  197. return syncDfd && syncDfd.promise();
  198. };
  199. Backbone.ajaxSync = Backbone.sync;
  200. Backbone.getSyncMethod = function(model) {
  201. if(model.localStorage || (model.collection && model.collection.localStorage)) {
  202. return Backbone.localSync;
  203. }
  204. return Backbone.ajaxSync;
  205. };
  206. // Override 'Backbone.sync' to default to localSync,
  207. // the original 'Backbone.sync' is still available in 'Backbone.ajaxSync'
  208. Backbone.sync = function(method, model, options) {
  209. return Backbone.getSyncMethod(model).apply(this, [method, model, options]);
  210. };
  211. return Backbone.LocalStorage;
  212. }));