25.02.2013 Views

Peter Lubbers - Pro HTML 5 Programming

Pro HTML 5 Programming

Pro HTML 5 Programming

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

230<br />

CHAPTER 9 ■ USING THE <strong>HTML</strong>5 WEB STORAGE API<br />

Listing 9-10. Displaying Stored Racer Data<br />

var storage = window.sessionStorage;<br />

// for each key in the storage database, display a new racer<br />

// location in the page<br />

for (var i=0; i < storage.length; i++) {<br />

var currRacer = storage.key(i);<br />

displayRacerLocation(currRacer, storage[currRacer]);<br />

}<br />

This is an important section of code. Here, we query the session for its length—in other words, the<br />

number of keys the storage contains. Then, we grab each key using storage.key() and store it into the<br />

currRacer variable, later using that variable to reference the key’s corresponding value with<br />

storage[currRacer]. Together, the key and its value represent a racer and that racer’s distance, which<br />

were stored on a visit to a previous page.<br />

Once we have a previously stored racer name and distance, we display them using the<br />

displayRacerLocation() function. This all happens very quickly on page load, causing the page to<br />

instantaneously fill its leader board with previously transmitted values.<br />

■ Note Our sample application relies on being the only application that stores values into the session storage<br />

area. If your application needs to share the storage object with other data, you will need to use a more nuanced<br />

key strategy than simply storing the keys at root level. We’ll look at another storage strategy in the “Practical<br />

Extras” section.<br />

Our last piece of load behavior is to hook up the page to the racer broadcast server using a simple<br />

WebSocket, as shown in Listing 9-11.<br />

Listing 9-11. Connecting to the WebSocket Broadcast Service<br />

// test to make sure that WebSocket is supported<br />

if (window.WebSocket) {<br />

}<br />

// the location where our broadcast WebSocket server is located<br />

url = "ws://websockets.org:7999/broadcast";<br />

socket = new WebSocket(url);<br />

socket.onopen = function() {<br />

document.getElementById("leaderboardStatus").inner<strong>HTML</strong> = "Leaderboard:�<br />

Connected!";<br />

}<br />

socket.onmessage = function(e) {<br />

dataReturned(e.data);<br />

}

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!