This example illustrates one method of serializing and recreating class instances by using the replacer
and reviver
parameters to JSON.stringify
and JSON.parse
respectively.
For this example, we'll use a class CaveMan, with a property discovered
that holds a Date
instance, and a method getName
.
freeze
and thaw
static methodsWe'll add the methods responsible for serializing and reconstituting instances to the CaveMan class as static methods.
We'll create a demo.FreezeThaw
namespace to hold our moving parts. In it, we'll add a method to pass to JSON.stringify
that calls our custom serializer, and another method to pass to JSON.parse
that detects the serialized structure and calls our thawing method.
We'll create a CaveMan instance and nest it in another object structure to illustrate how the thawing process still operates normally for all other data.
Date
instanceThe reviver function passed to JSON.parse
is applied to all key:value pairs in the raw parsed object from the deepest keys to the highest level. In our case, this means that the name
and discovered
properties will be passed through the reviver, and then the object containing those keys will be passed through.
We'll take advantage of this and apply YAHOO.lang.JSON.stringToDate
to all string values, which will reconstitute Date instances when they match the iso8601 UTC format that JSON serializes Dates to by default.
Now when the reviver function is evaluating the object it determines to be a CaveMan, the discovered
property is correctly containing a Date
instance.
You'll note there are two freeze and thaw operations going on in this example. One for our CaveMan class and one for Date
instances. Their respective serialization and recreation techniques are different. You are free to decide the serialized format of your objects. Choose whatever makes sense for your application.
Now we add the event handlers to the example buttons to call JSON.stringify
and parse
with our example.cryo
and example.revive
methods, respectively.
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.
Note: Logging and debugging is currently turned off for this example.
Copyright © 2009 Yahoo! Inc. All rights reserved.
Privacy Policy - Terms of Service - Copyright Policy - Job Openings