HTML and CSS Reference
In-Depth Information
Alternaively, local storage provides an array syntax to access the data:
localStorage['key here'] = "value goes here"; // set the value
localStorage['key here']; // get the value
Since the stored value is in the string format, we should postprocess the loaded data to the
format we need. For example, if we saved the coins, we need to type cast the string back to
the number:
localStorage['coins']= 123; // stored as "123"
var savedCoins = localStorage['coins'] * 1; // x1 to make it a number
We have the following things to save in the local storage:
F The amount of coins
F The amount of diamonds
F The list of buildings
What about the list of buildings, which is an array of objects with values?
We can sill save an object by convering the object into a string. Technically, we can use
any kind of string serializaion but JSON is a good choice here. We can use the built-in JSON
object. It provides two methods to convert an object into a string and vice versa. They are
JSON.stringify and JSON.parse . When we convert an object into a string, we use the
stringify method. After we load the serialized string back from the storage, we parse it
into a JavaScript object:
JSON.stringify(obj) serializes the given object into string.
JSON.parse(string) parses the string into object.
We can't assume that the value exists in the local storage. It may be the irst ime a player
opens the game. It can also be that the player deleted the local data manually. Either way,
it will lead to an undefined value when we try to retrieve the value from the local storage.
It is a good pracice to have a default value in case the local storage returns an undeined
result. The following code is how we add the default value:
game.coins = localStorage['city.coins']*1 || 10; // default 10 coins
For a more detailed discussion on the local storage, you can refer to the guide on Mozilla
( )
or the online topic Dive into HTML5 , by Mark Pilgrim , published by O'Reilly Media at .
Search WWH ::

Custom Search