Thread: Cookies and OOP
View Single Post
Old 12-16-2002, 09:26 PM   PM User | #5
jkd
Senior Coder

 
jkd's Avatar
 
Join Date: May 2002
Location: metro DC
Posts: 3,163
Thanks: 1
Thanked 18 Times in 18 Posts
jkd will become famous soon enough
I have this kicking around my hard drive:
Code:
var CookieJar = {
	Cookie: function(name, value, expires, domain, path, secure) {
		this.name = name;
		this.value = value;
		this.expires = expires;
		this.domain = domain;
		this.path = path;
		this.secure = secure;
		this.toString = function() {
			return this.name + '=' + escape(this.value) + ((typeof this.expires != 'undefined' && this.expires.constructor == Date) ? ('; expires=' + this.expires.toUTCString()) : '') + ((typeof this.domain != 'undefined') ? ('; domain=' + this.domain) : '') + ((typeof this.path != 'undefined') ? ('; path=' + this.path) : '') + ((typeof this.secure != 'undefined') ? '; secure' : '');
		}
		this.bake = function() {
			CookieJar.cookies[this.name] = this;
			document.cookie = this.toString();
		}
		this.eat = function () {
			delete CookieJar.cookies[this.name];
			document.cookie = this.name + '=' + escape(this.value) + '; expires=Thu, 01-Jan-70 00:00:01 GMT';
		}
	},
	fill: function() {
		CookieJar.cookies = document.cookie.match(/([^ ;]+=[^;]+(?:; expires=[^;])?(?:; domain=[^;])?(?:; path=[^;])?(?:; secure)?)/g);
		var i, name, value, expires, domain, path, split;
		for (i = 0; i < this.cookies.length; i++) {
			split = CookieJar.cookies[i].split('=');
			name = split[0];
			value = unescape(split[1].split(';')[0]);
			expires = new Date((typeof split[2] == 'undefined') ? undefined : split[2].split(';')[0]);
			domain = (typeof split[3] == 'undefined') ? undefined : split[3].split(';')[0];
			path = (typeof split[4] == 'undefined') ? undefined : split[4].split(';')[0];
			secure = (typeof split[4].split('; ')[1] == 'undefined') ? undefined : true;
			CookieJar.cookies[name] = new CookieJar.Cookie(name, value, (isNaN(expires.valueOf()) ? undefined : expires), domain, path, secure);
		}
	},
	empty: function() {
		for (var i in CookieJar.cookies) {
			if (CookieJar.cookies[i].constructor == CookieJar.Cookie)
				CookieJar.cookies[i].eat();
			else
				delete CookieJar.cookies[i];
		}
	}
}

CookieJar.fill();
Something I wrote once to mess around with cookies, but never really used.

But it does have playful names .
__________________
jasonkarldavis.com
jkd is offline   Reply With Quote