cookie.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /**
  2. * Handles the cookie used by several JavaScript functions
  3. *
  4. * Only a single cookie is written and read. You may only save
  5. * simple name-value pairs - no complex types!
  6. *
  7. * You should only use the getValue and setValue methods
  8. *
  9. * @author Andreas Gohr <andi@splitbrain.org>
  10. * @author Michal Rezler <m.rezler@centrum.cz>
  11. */
  12. var DokuCookie = {
  13. data: {},
  14. name: 'DOKU_PREFS',
  15. /**
  16. * Save a value to the cookie
  17. *
  18. * @author Andreas Gohr <andi@splitbrain.org>
  19. */
  20. setValue: function(key,val){
  21. var text = [],
  22. _this = this;
  23. this.init();
  24. if (val === false){
  25. delete this.data[key];
  26. }else{
  27. val = val + "";
  28. this.data[key] = val;
  29. }
  30. //save the whole data array
  31. jQuery.each(_this.data, function (key, val) {
  32. if (_this.data.hasOwnProperty(key)) {
  33. text.push(encodeURIComponent(key)+'#'+encodeURIComponent(val));
  34. }
  35. });
  36. jQuery.cookie(this.name, text.join('#'), {expires: 365, path: DOKU_COOKIE_PARAM.path, secure: DOKU_COOKIE_PARAM.secure});
  37. },
  38. /**
  39. * Get a Value from the Cookie
  40. *
  41. * @author Andreas Gohr <andi@splitbrain.org>
  42. * @param def default value if key does not exist; if not set, returns undefined by default
  43. */
  44. getValue: function(key, def){
  45. this.init();
  46. return this.data.hasOwnProperty(key) ? this.data[key] : def;
  47. },
  48. /**
  49. * Loads the current set cookie
  50. *
  51. * @author Andreas Gohr <andi@splitbrain.org>
  52. */
  53. init: function(){
  54. var text, parts, i;
  55. if(!jQuery.isEmptyObject(this.data)) {
  56. return;
  57. }
  58. text = jQuery.cookie(this.name);
  59. if(text){
  60. parts = text.split('#');
  61. for(i = 0; i < parts.length; i += 2){
  62. this.data[decodeURIComponent(parts[i])] = decodeURIComponent(parts[i+1]);
  63. }
  64. }
  65. }
  66. };