HTML and CSS Reference
In-Depth Information
Storing more than strings
Yo u c a n w of r k a r of u n d t h e “ s t r i n g i f y i n g ” of f of b j e c t s b y m a k i n g u s e
of JSON. Since JSON uses text to represent a JavaScript object,
we can use this to store objects and convert stored data back
into objects, but it's really a wrapper for this bug. It depends
whether the browsers intend to support the any data storage
eventually, but this is easy to test for. However, it would require
putting a wrapper on the set and get methods, which (depend-
ing on your application) may or may not be an option.
All the latest browsers (either nightly or fi nal releases) support
native JSON encoding using the JSON.parse and JSON.stringify
methods. For those browsers that don't have JSON support,
we can include Douglas Crockford's JSON library (available at
http://www.json.org/json2.js ).
Now you can wrap setItem and getItem as follows:
var videoDetails = {
author: 'bruce',
description: 'how to leverage synergies',
rating: '-2'
};
NOTE JSON (JavaScript
Object Notation) is a text
based open standard for repre-
senting data. The specifi cation
found at http://json.org is so
simple it actually fi ts on the back
of a business card!
sessionStorage.setItem('videoDetails', JSON.
¬ stringify(videoDetails) );
// later on, as in page reloads later, we can extract the
¬ stored data
var videoDetails = JSON.parse(sessionStorage.getItem
¬ ('videoDetails'));
As I stated in the API overview section, if the key doesn't exist
in the storage object, then it will return null. This isn't a problem
for the native JSON parsers as JSON.parse(null) returns null—as
you would expect. However, for Douglas Crockford's JavaScript
version, passing null will throw an error. So if you know it's pos-
sible that Douglas' JSON JavaScript library is being loaded, pro-
tect against this error by using the following:
var videoDetails = JSON.parse(sessionStorage.getItem
¬ ('videoDetails') || 'null');
This ensures that if null is returned from the getItem method,
you pass in a JSON-encoded version of null, and thus the
JavaScript based JSON parser won't break.
 
Search WWH ::




Custom Search