2 Script: Hash.Cookie.js
\r
3 Stores and loads an Hash as a cookie using Json format.
\r
8 Inherits all the methods from <Hash>, additional methods are save and load.
\r
9 Hash json string has a limit of 4kb (4096byte), so be careful with your Hash size.
\r
10 Creating a new instance automatically loads the data from the Cookie into the Hash.
\r
11 If the Hash is emptied, the cookie is also removed.
\r
14 name - the key (name) for the cookie
\r
15 options - options are identical to <Cookie> and are simply passed along to it.
\r
16 In addition, it has the autoSave option, to save the cookie at every operation. defaults to true.
\r
20 var fruits = new Hash.Cookie('myCookieName', {duration: 3600});
\r
25 fruits.set('melon', 'green');
\r
26 fruits.get('lemon'); // yellow
\r
28 // ... on another page ... values load automatically
\r
30 var fruits = new Hash.Cookie('myCookieName', {duration: 365});
\r
31 fruits.get('melon'); // green
\r
33 fruits.erase(); // delete cookie
\r
37 Hash.Cookie = Hash.extend({
\r
39 initialize: function(name, options){
\r
41 this.options = $extend({'autoSave': true}, options || {});
\r
47 Saves the Hash to the cookie. If the hash is empty, removes the cookie.
\r
50 Returns false when the JSON string cookie is too long (4kb), otherwise true.
\r
54 var login = new Hash.Cookie('userstatus', {autoSave: false});
\r
58 'credentials': [4, 7, 9]
\r
60 login.set('last_message', 'User logged in!');
\r
62 login.save(); // finally save the Hash
\r
67 if (this.length == 0){
\r
68 Cookie.remove(this.name, this.options);
\r
71 var str = Json.toString(this.obj);
\r
72 if (str.length > 4096) return false; //cookie would be truncated!
\r
73 Cookie.set(this.name, str, this.options);
\r
79 Loads the cookie and assigns it to the Hash.
\r
83 this.obj = Json.evaluate(Cookie.get(this.name), true) || {};
\r
89 Hash.Cookie.Methods = {};
\r
90 ['extend', 'set', 'merge', 'empty', 'remove'].each(function(method){
\r
91 Hash.Cookie.Methods[method] = function(){
\r
92 Hash.prototype[method].apply(this, arguments);
\r
93 if (this.options.autoSave) this.save();
\r
97 Hash.Cookie.implement(Hash.Cookie.Methods);