jquery.storage.js 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /*!
  2. * jquery.storage.js 0.0.3 - https://github.com/yckart/jquery.storage.js
  3. * The client-side storage for every browser, on any device.
  4. *
  5. * Copyright (c) 2012 Yannick Albert (http://yckart.com)
  6. * Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php).
  7. * 2013/02/10
  8. **/
  9. ;(function($, window, document) {
  10. 'use strict';
  11. $.map(['localStorage', 'sessionStorage'], function( method ) {
  12. var defaults = {
  13. cookiePrefix : 'fallback:' + method + ':',
  14. cookieOptions : {
  15. path : '/',
  16. domain : document.domain,
  17. expires : ('localStorage' === method) ? { expires: 365 } : undefined
  18. }
  19. };
  20. try {
  21. $.support[method] = method in window && window[method] !== null;
  22. } catch (e) {
  23. $.support[method] = false;
  24. }
  25. $[method] = function(key, value) {
  26. var options = $.extend({}, defaults, $[method].options);
  27. this.getItem = function( key ) {
  28. var returns = function(key){
  29. return JSON.parse($.support[method] ? window[method].getItem(key) : $.cookie(options.cookiePrefix + key));
  30. };
  31. if(typeof key === 'string') return returns(key);
  32. var arr = [],
  33. i = key.length;
  34. while(i--) arr[i] = returns(key[i]);
  35. return arr;
  36. };
  37. this.setItem = function( key, value ) {
  38. value = JSON.stringify(value);
  39. return $.support[method] ? window[method].setItem(key, value) : $.cookie(options.cookiePrefix + key, value, options.cookieOptions);
  40. };
  41. this.removeItem = function( key ) {
  42. return $.support[method] ? window[method].removeItem(key) : $.cookie(options.cookiePrefix + key, null, $.extend(options.cookieOptions, {
  43. expires: -1
  44. }));
  45. };
  46. this.clear = function() {
  47. if($.support[method]) {
  48. return window[method].clear();
  49. } else {
  50. var reg = new RegExp('^' + options.cookiePrefix, ''),
  51. opts = $.extend(options.cookieOptions, {
  52. expires: -1
  53. });
  54. if(document.cookie && document.cookie !== ''){
  55. $.map(document.cookie.split(';'), function( cookie ){
  56. if(reg.test(cookie = $.trim(cookie))) {
  57. $.cookie( cookie.substr(0,cookie.indexOf('=')), null, opts);
  58. }
  59. });
  60. }
  61. }
  62. };
  63. if (typeof key !== "undefined") {
  64. return typeof value !== "undefined" ? ( value === null ? this.removeItem(key) : this.setItem(key, value) ) : this.getItem(key);
  65. }
  66. return this;
  67. };
  68. $[method].options = defaults;
  69. });
  70. }(jQuery, window, document));