Local Storage Utility


SUBMITTED BY: Guest

DATE: Feb. 20, 2014, 6:13 p.m.

FORMAT: JavaScript

SIZE: 2.6 kB

HITS: 1566

  1. /**
  2. * Storage Utility
  3. *
  4. * Used for File Management
  5. */
  6. var Storage = function() {};
  7. Storage.prototype = {
  8. /**
  9. * Initialise
  10. *
  11. * Run when the Utility is created
  12. */
  13. init: function UtilStorageInit() {
  14. if (typeof localStorage !== 'undefined') {
  15. this._localStorageAvailable = true;
  16. } else {
  17. this._localStorageAvailable = false;
  18. }
  19. this.configureStorage();
  20. },
  21. /**
  22. * Configure Storage
  23. *
  24. * If Local Storage is available then use Cookies
  25. *
  26. * @returns {Storage}
  27. */
  28. configureStorage: function Storage() {
  29. if (this._localStorageAvailable) {
  30. // as we have local storage create a storage object with required functions
  31. this.save = function StorageSave(id, data) {
  32. localStorage[id] = JSON.stringify(data);
  33. };
  34. this.load = function StorageLoad(id) {
  35. var data = localStorage[id];
  36. if (data === null || !data)
  37. return null;
  38. return JSON.parse(data);
  39. };
  40. this.clear = function StorageClear(id) {
  41. try {
  42. localStorage[id] = null;
  43. } catch(e) {
  44. alert(e);
  45. }
  46. };
  47. } else {
  48. // no local storage so use the old cookie approach
  49. this.log('localStorage NOT supported', 'warning');
  50. this.save = function StorageSave(id, data) {
  51. document.cookie = (id) + "=" + encodeURIComponent(JSON.stringify(data));
  52. };
  53. this.load = function StorageLoad(id) {
  54. var s = "; " + document.cookie + ";", p = s.indexOf("; " + id + "=");
  55. if (p < 0)
  56. return "";
  57. p = p + id.length + 3;
  58. var p2 = s.indexOf(";", p + 1);
  59. return JSON.parse(decodeURIComponent(s.substring(p, p2)));
  60. };
  61. this.clear = function StorageClear(id) {
  62. // TODO: This
  63. };
  64. }
  65. try {
  66. delete this._localStorageAvailable;
  67. delete this.init;
  68. delete this.configureStorage;
  69. delete this.__proto__.init;
  70. delete this.__proto__.configureStorage;
  71. } catch(e) {};
  72. }
  73. };

comments powered by Disqus