This example shows how to get and set subcookies as well as using conversion functions when retrieving subcookie values.
Keep an eye on the Logger console at right to view the log messages associated with this example.
This example begins by setting up a local reference to the Cookie utility:
1 | var Cookie = YAHOO.util.Cookie; |
view plain | print | ? |
The next three lines attempt to read the values stored in subcookies of the "example" cookie:
1 | var name = Cookie.getSub("example", "name"); |
2 | var today = Cookie.getSub("example", "today", function(value){ |
3 | return new Date(value); |
4 | }); |
5 | var count = Cookie.getSub("example", "count", Number); |
view plain | print | ? |
The "name" subcookie stores a string so it is retrieved without specifying a third argument. The "today"
subcookie stores a date string, which should be converted to a Date
object upon retrieval; the third argument
of getSub()
is specified as a custom function that will convert the returned value into a Date
object.
The "count" subcookie contains a number and is converted to an actual JavaScript number by passing in the native
Number
function. If any of these subcookies don't exist, getSub()
returns null
(this should
be the case the first time you run the example). The retrieved values are output in the logger.
After that, new values are assigned to the various subcookies:
1 | Cookie.setSub("example", "name", "Yahoo!"); |
2 | Cookie.setSub("example", "today", (new Date()).toString()); |
3 | Cookie.setSub("example", "count", Math.round(Math.random() * 30)); |
view plain | print | ? |
The "name" subcookie is set to "Yahoo!", the "today" subcookie is set to the value
of a new Date
object, outputting its string representation, and the "count" subcookie is filled
with a random number. The next time you run the example, the subcookies should have these values.
You can load the necessary JavaScript and CSS for this example from Yahoo's servers. Click here to load the YUI Dependency Configurator with all of this example's dependencies preconfigured.
INFO 314ms (+311) 4:21:05 PM:
LogReader instance0
LogReader initialized
INFO 3ms (+0) 4:21:05 PM:
global
The subcookie 'count' is 'null'(object)
INFO 3ms (+0) 4:21:05 PM:
global
The subcookie 'today' is 'null'(object)
INFO 3ms (+3) 4:21:05 PM:
global
The subcookie 'name' is 'null'(object)
INFO 0ms (+0) 4:21:05 PM:
global
Logger initialized
Copyright © 2010 Yahoo! Inc. All rights reserved.
Privacy Policy - Terms of Service - Copyright Policy - Job Openings