HashCookie Class

My first experience with JavaScript involved creating roll-over effects for websites, I actually thought that was what JavaScript was built for.  I've come a long way since then in understanding the potential of JavaScript as a programming language.  One interesting aspect of the language is its ability to dynamically add properties to an object.

The HashCookie class uses this feature to create an object that works like a hash table so that referencing asp.net multi-valued cookies would be as simple as typing objectInstance[propertyName].  The code below is the complete HashCookie object.

function HashCookie(cookieName)
{
  var cookieValue = getRawCookieValue();
  if (cookieValue != null)
  {
    var nameValuePairs = cookieValue.split('&');
    for (var i = 1; i < nameValuePairs.length; i++)
    {
      var nameValue = nameValuePairs[i].split('=');
      this[unescape(nameValue[0])] = unescape(nameValue[1]);
    }
  }
 
  this.save = function()
  {
    var cookieValue = cookieName + '=';
    for (memberName in this)
    {
      if (typeof this[memberName] == 'function') continue;
      cookieValue += '&' + escape(memberName) + '=' + escape(this[memberName]);
    }
    var expireDate = new Date();
    expireDate.setFullYear(expireDate.getFullYear() + 1);

    document.cookie = cookieValue + '; expires=' + expireDate.toGMTString() + '; path=/';
  }
 
  this.remove = function()
  {
    for (memberName in this)
    {
      if (typeof this[memberName] == 'function') continue;
      delete this[memberName];
    }
    document.cookie = cookieName + '=; expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/';
  }
 
  function getRawCookieValue()

  {
    var start = document.cookie.indexOf(cookieName + '=');
    if (start == -1)
return null;
    start += cookieName.length + 1;
    var end = document.cookie.indexOf(';', start);
    if (end == -1)
end = document.cookie.length - 1;
    return document.cookie.substring(start, end);
  }
}

Here's an example of how to use the object:

var wsCookie = new HashCookie('Workspace');

wsCookie['bgColor'] = document.getElementById('BGColorPicker').value;
wsCookie['fgColor'] = document.getElementById('FGColorPicker').value;
wsCookie.save();

I'm not sure if this is the most efficient way to create the HashCookie class I originally envisioned, but it was an interesting exercise. 

Related Entries

no entries found