jquery.storage.js 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. define([], function() {
  10. ;(function($, window, document) {
  11. 'use strict';
  12. $.map(['localStorage', 'sessionStorage'], function( method ) {
  13. var defaults = {
  14. cookiePrefix : 'fallback:' + method + ':',
  15. cookieOptions : {
  16. path : '/',
  17. domain : document.domain,
  18. expires : ('localStorage' === method) ? { expires: 365 } : undefined
  19. }
  20. };
  21. try {
  22. $.support[method] = method in window && window[method] !== null;
  23. } catch (e) {
  24. $.support[method] = false;
  25. }
  26. $[method] = function(key, value) {
  27. var options = $.extend({}, defaults, $[method].options);
  28. this.getItem = function( key ) {
  29. var returns = function(key){
  30. return JSON.parse($.support[method] ? window[method].getItem(key) : $.cookie(options.cookiePrefix + key));
  31. };
  32. if(typeof key === 'string') return returns(key);
  33. var arr = [],
  34. i = key.length;
  35. while(i--) arr[i] = returns(key[i]);
  36. return arr;
  37. };
  38. this.setItem = function( key, value ) {
  39. value = JSON.stringify(value);
  40. return $.support[method] ? window[method].setItem(key, value) : $.cookie(options.cookiePrefix + key, value, options.cookieOptions);
  41. };
  42. this.removeItem = function( key ) {
  43. return $.support[method] ? window[method].removeItem(key) : $.cookie(options.cookiePrefix + key, null, $.extend(options.cookieOptions, {
  44. expires: -1
  45. }));
  46. };
  47. this.clear = function() {
  48. if($.support[method]) {
  49. return window[method].clear();
  50. } else {
  51. var reg = new RegExp('^' + options.cookiePrefix, ''),
  52. opts = $.extend(options.cookieOptions, {
  53. expires: -1
  54. });
  55. if(document.cookie && document.cookie !== ''){
  56. $.map(document.cookie.split(';'), function( cookie ){
  57. if(reg.test(cookie = $.trim(cookie))) {
  58. $.cookie( cookie.substr(0,cookie.indexOf('=')), null, opts);
  59. }
  60. });
  61. }
  62. }
  63. };
  64. if (typeof key !== "undefined") {
  65. return typeof value !== "undefined" ? ( value === null ? this.removeItem(key) : this.setItem(key, value) ) : this.getItem(key);
  66. }
  67. return this;
  68. };
  69. $[method].options = defaults;
  70. });
  71. }(jQuery, window, document));
  72. });