Friday, August 7, 2009

Loading and Saving TaffyDB data from cookies

I flopped around a good long time over this one:

I'm using cookies as a datastore, but had an issue with TaffyDB not stringify correctly. The TaffyDB author, Ian Smith provided some critical help, and here is the working (though probably not ideal solution):

 function clone(o) {  
if(typeof(o) != 'object') return o;
if(o == null) return o;
var newO = new Object();
for(var i in o) newO[i] = clone(o[i]);
return newO;
}
function sav(){
var cookieData = clone(chardata);
cookieData.skills = cookieData.skills.get();
cookieData = TAFFY.JSON.stringify(cookieData);
var d = new Date(2020, 02, 02);
document.cookie = 'chardata=' + cookieData + ';expires=' + d.toUTCString();
}
function lod(){
if (document.cookie.length > 0) {
c_start = document.cookie.indexOf("chardata=");
if (c_start != -1) {
c_start = c_start + 9 //c_name.length + 1;
c_end = document.cookie.indexOf(";", c_start);
if (c_end == -1) {
c_end = document.cookie.length;
}
cookie_data = document.cookie.substring(c_start, c_end);
chardata = TAFFY.JSON.parse(unescape(cookie_data));
chardata.skills = TAFFY(chardata.skills);
}
}
}


The biggest stumbling block came from the fact that assigning chardata to a temporary var (and then stringify-ing it) changed my Taffy object into a string. Cloning the db fixed the issue.

No comments: