Save and Restore with Local Storage

Free HTML5 Game Tutorial for Beginners: Page 20

Overview What's Local Storage? Check for Local Storage Restore from Local Storage Save to Local Storage Tips Summary Source: Controller Requests Score Source: Model Loads the Score Source: Model Obtains Local Storage Source: Save Model Data Source: Save to Local Storage Source: Model Code
Score Function Diagram

Overview

Learn how to save and restore data with HTML5's local storage feature. This tutorial explains the basics of local storage. This article demonstrates how to retrieve values from local storage when an online application loads. This lesson shows how to save values to local storage with JavaScript.

The example Surface Game demonstrates saving and restoring game data. This tutorial explains how to save the player's score, question number, and level, whenever they change. This article shows how to start the game again, where the player left off.

The player's score, level, and question number represent part of the model component of the MVC Design Pattern.

The example Surface Game saves game data whenever the score changes. When the player returns to the game, load previously saved data. Use HTML5 local storage to save and restore, if it's available, otherwise use cookies. The Score Function Diagram above, illustrates restoring the score with either local storage or cookies.

What's Local Storage?

Local storage consists of name-value properties, which the programmer assigns, and the browser maintains. For example the name for the Surface Game's score is sgscore. The value for the score, level, and current question are Number types. However save any valid JavaScript type to local storage. Use any valid JavaScript name, as well.

Local storage names are prefixed with sg to indicate Surface Game. Multiple applications access local storage. Therefore use a naming convention which reduces the possibility two online programs will attempt to modify the same variables.

Not every browser enables local storage. If local storage is enabled, then if(typeof(Storage)!=="undefined") will return true. If not, then use cookies to save and restore data.

To save the score, cast the value to the Number type, then assign the value to local storage:
localStorage.sgscore = Number(iScore)

To restore the score, verify the property exists in local storage, then retrieve it. See the following short listing for an example which retrieves the Surface Game's score from local storage. Built in variable localStorage exists, if local storage is enabled in the current browser.

if (localStorage.sgscore){

 iScore = Number
 (

 localStorage.sgscore

 );

}

Save and Restore Data

Assign an onload event listener to the Web page to restore any pre-existing data. Assign an onunload event listener to save any current data. The following short listing retreives the score through function loadGame() and saves the score through function stopGame().

<body onload="loadGame(0)"  
 onresize="resizeCanvas()" 
 onunload="stopGame()"
>

Start the Game: Load the Score

The function loadGame() is the Surface Game's onload event listener. loadGame() is defined in surface-game-control.js. loadGame() calls the model's initialization function scoreModelGet(). Function scoreModelGet() returns any stored data for the game. Remember local storage is part of the model component in the MVC design pattern. Therefore surface-game-model.js declares functions which save and restore data.

Function scoreModelGet() returns data from local storage if it's available, otherwise scoreModelGet() returns any valid data from cookies.

Check for Local Storage

if(typeof(Storage)!=="undefined") tests to determine if the current browser has enabled local storage. If local storage is enabled, then one call to the Surface Game's localStorageGet() function, obtains all previously saved game data. The function diagram illustrates the call stack to restore local storage or cookies, with the example Surface Game. Function scoreModelGet() calls scoreGet(), which checks for local storage, then calls localStorageGet().

Restore from Local Storage

Before attempting to access the value from a property of local storage, verify the property isn't null. The property equals null if the browser cache was cleared, or the property has never been saved. Local storage might exist but individual properties might not. The following code demonstrates how to retrieve the level. The following short listing looks quite a lot like the previous listing which obtained the score from local storage.

if (localStorage.sglevel){

 iLvl = Number
 (

  localStorage.sglevel

 );

}		
		

After localStorageGet() obtains all previously saved data, function scoreModelGet() returns the data to the controller. The data's returned as an Array with the following values.

[iLvl,iIdx,iScore]

Save to Local Storage

The example Surface Game's controller saves the score every time the score, level, or question, changes. Whenever the player taps the Final Answer button, function tapAnswer() processes the score, question number, and level. tapAnswer() calls scoreModelSet(level,index,score). If local storage is enabled, then scoreModelSet() calls function localStorageSet(), listed below.

function localStorageSet(){ 	
 localStorage.sgscore = Number(
  iScore
 );
 
 localStorage.sglevel = Number(
  iLvl
 ); 			
 
 localStorage.sgindex = Number(
  iIdx
 );
}

Tips

Be sure to save and restore identical property names. For example, if code saves to localStorage.sglevel, then code must test localStorage.sglevel for null, before restoring the property sglevel. The capitalization and spelling must match.

Summary

This lesson explained how to save and restore data with HTML5's local storage feature. This tutorial explained the basics of local storage. This article demonstrated how to retrieve values from local storage when an online application loads. This lesson showed how to save values to local storage with JavaScript.

The example Surface Game demonstrates saving and restoring game data. This tutorial explained how to save the player's score, question number, and level, whenever they change. This article demonstrated how to start the game again, where the player left off.

The player's score, level, and question number represent part of the model component of the MVC Design Pattern.

The example Surface Game saves game data whenever the score changes. When the player returns to the game, load previously saved data. Use HTML5 local storage to save and restore, if it's available, otherwise use cookies. The Score Function Diagram above, illustrates restoring the score with either local storage or cookies.

For the next tutorial, tap the image icon containing text which says Next Lesson, or the right pointing arrow at the bottom of the page.

Previous Page Next Page
Copyright © 2015 Seven Thunder Software. All Rights Reserved.