HTML5 Guidelines for Web Developers

(coco) #1
8.4 Example: Click to tick! 227

canvas.onclick = function(evt) {
checkPosition(evt);
};
...
startGame(0);
};


The functions addOpt() and _get() will probably be new to you. These are two
auxiliary functions; addOpt() serves to assemble the string for a new option ele-
ment, and _get() allows efficient access to the elements in the DOM tree (via
their ID). The HTML element with the ID selGame is the selection list of all games.
This list is set to the first element with selectedIndex = 0. If another item in this
list is selected, the startGame function is activated with this new value.


An event handler for the mouse click event is assigned to the canvas element and
calls the checkPosition function. Then the first game is started.


Because many functions of the GameLib are designed to ensure that the game
runs properly and are not directly connected with Web Storage or the offline
cache, we will not describe them in great detail here. If you are curious, you can
peek at the source code for the JavaScript library click2tick.js. But more relevant
for our offline chapter is the JavaScript code involving the Storage interface with
localStorage: We will use it when saving a game:


// store basic data in localStorage, add hostname
// and timestamp
var ts = new Date().getTime();
var id = "click2tick"+game.store.gid+""+ts;
game.store.hostname = location.hostname;
game.store.ts = ts;
localStorage.setItem(id, JSON.stringify(game.store));


To ensure the keys in localStorage are unique, they are created by combining
a prefix string (click2tick), a game ID (game.store.gid), and a timestamp (ts)
connected by an underline (_).


The game.store structure is saved as a value with all results in the form of a JSON
string. The following listing shows the value after five out of eight questions have
been correctly answered at the end of the game. The key for the following entry
is click2tick_0001_1281026695083 (see also Figure 8.8):


{ "gid":"0001","game":"Downtown Paris",
"questions":8,"correct":5,"percent":63,
"hostname":"html5.komplett.cc", "ts":1281026695083
}

Free download pdf