This example shows how to get and set subcookies as well as using conversion functions when retrieving subcookie values.
The first three lines attempt to read the values stored in subcookies of the "example" cookie:
var name = Y.Cookie.getSub("example", "name"); var today = Y.Cookie.getSub("example", "today", function (value) { return new Date(value); }); var count = Y.Cookie.getSub("example", "count", Number);
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 shown in the browser console.
After that, new values are assigned to the various subcookies:
Y.Cookie.setSub("example", "name", "Yahoo!"); Y.Cookie.setSub("example", "today", (new Date()).toString()); Y.Cookie.setSub("example", "count", Math.round(Math.random() * 30));
The "name" subcookie is set to "Yahoo!", the "today" subcookie is set to the value of a new Date
object as a string, and the "count" subcookie is filled with a random number. The next time you run the example, the subcookies should have these values.
<pre id="results"></pre> <script> YUI().use('cookie', 'node', function (Y) { var results = Y.one('#results'), log = function(str) { results.append(str + '<br>'); }; //set subcookie values Y.Cookie.setSub("example", "name", "Yahoo!"); Y.Cookie.setSub("example", "today", (new Date()).toString()); Y.Cookie.setSub("example", "count", Math.round(Math.random() * 30)); //get subcookie values var name = Y.Cookie.getSub("example", "name"); var today = Y.Cookie.getSub("example", "today", function (value) { return new Date(value); }); var count = Y.Cookie.getSub("example", "count", Number); log("The subcookie 'name' is '" + name + "' (" + (typeof name) + ")"); log("The subcookie 'today' is '" + today + "' (" + (typeof today) + ")"); log("The subcookie 'count' is '" + count + "' (" + (typeof count) + ")"); }); </script>