Skip to content

Instantly share code, notes, and snippets.

@andy0130tw
Last active August 29, 2015 13:56
Show Gist options
  • Save andy0130tw/8860854 to your computer and use it in GitHub Desktop.
Save andy0130tw/8860854 to your computer and use it in GitHub Desktop.
CookieObject
//CookieObject v1 by Andy Pan
// You can use the small piece of code to r/w
// > Cookies, not losing its structure of an object.
// > All complex contents will be automatically
// > en(de)code, but simple contents won't
// > so that you can access them without pain.
// Assume JSON.parse() and JSON.stringify().
// Use it with jquery.cookie by carhartl:
// > https://github.com/carhartl/jquery-cookie
//Manual
// Call cookieObject.init() to read in all.
// This is optional. You can use it normally
// without doing this. Useful when you only
// need to use cookie as a cache.
// Once the cookie is read,
// > its form of object will be cached
// > and be updated when saving it back.
// An alternative way to use is writing the
// > data into cookie, and manually calling
// > cookieObject.flush(...). If a key is not
// > specified, all entries will be flushed.
//To save/load a cookie, simply substitute
// > $.cookie(...) to
// > cookieObject.save[load](...);
//To-dos
// * Make it a fallback for localStroage.
//Good luck!
var cookie=null;
var cookieObject={
init:function(){
cookie={};
var raw=$.cookie();
for(var x in raw)cookieObject.load(x);
},
flush:function(key,option){
if(key)return cookieObject.save(key,cookie[key],option);
for(var x in cookie)cookieObject.save(x,cookie[x],option);
},
save:function(key,obj,option){
cookie[key]=obj;
if(obj instanceof Object)val=JSON.stringify(obj);
else val=obj;
return $.cookie(key,val,option);
},
load:function(key){
if(cookie[key])return cookie[key];
var val=$.cookie(key);
try{
return cookie[key]=JSON.parse(val);
}catch(e){
return cookie[key]=val;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment