HTML and CSS Reference
In-Depth Information
alert("Data is not of date type!");
This code stores a date in localStorage . It then tries to access the year part of the date without
performing any conversion. This results in an error, as indicated by the alert box. The second attempt
parses the stored string into a Date object and then outputs its year. As you might have already guessed,
the second attempt gives correct results.
In Listing 7-3, the date is stored in the localStorage object using the default JavaScript format (for
example, Thu Mar 01 2012 00:00:00 GMT+0530 [India Standard Time]). In many cases, you may be using an
input field as a date picker (you can do that in by setting the type attribute to date). The date picker returns
dates in yyyy-MM-dd format. This format is also safe to store directly in localStorage because it can be
easily parsed back into a JavaScript Date object later.
Storing objects sounds complex at first, but luckily most browsers support a handy way to convert
objects into strings and vice versa. As far as JavaScript is concerned, objects are represented in JSON
format; using the JSON.stringify() and JSON.parse() methods, you can easily convert a JSON object into
a string and parse its string representation back into an object. Listing 7-4 shows how to do this
Listing 7-4. Converting JSON Objects
$(document).ready(function () {
var storage = window.localStorage;
var object1 = { "Name": "Tom", "Age": 50 };
storage["object"] = JSON.stringify(object1);
var object2 = JSON.parse(storage["object"]);
alert(object2.Name + " (" + object2.Age + " years)");
This code defines a JSON object with two properties: Name and Age . While storing the JSON object into
localStorage , the JSON.stringify() method converts the JSON object into its string representation. While
retrieving the data from localStorage , the JSON.parse() method reconstructs the object. The alert box
then correctly outputs the Name and Age properties (Figure 7-3).
Figure 7-3. Dealing with JSON objects
Search WWH ::

Custom Search