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.

Download from Wow! eBook <br />

222<br />

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

As you can see, the name storage is used to indicate interest in storage events. Any time a Storage<br />

event—either sessionStorage or localStorage—for that origin is raised any registered event listener will<br />

receive the storage event as the specified event handler. The storage event itself takes the form shown in<br />

Listing 9-3.<br />

Listing 9-3. The StorageEvent Interface<br />

interface StorageEvent : Event {<br />

readonly attribute DOMString key;<br />

readonly attribute any oldValue;<br />

readonly attribute any newValue;<br />

readonly attribute DOMString url;<br />

readonly attribute Storage storageArea;<br />

};<br />

The StorageEvent object will be the first object passed to the event handler, and it contains all the<br />

information necessary to understand the nature of the storage change.<br />

• The key attribute contains the key value that was updated or removed in the<br />

storage.<br />

• The oldValue contains the previous value corresponding to the key before it was<br />

updated, and the newValue contains the value after the change. If the value was<br />

newly added, the oldValue will be null, and if the value has been removed, the<br />

newValue will be null.<br />

• The url will point to the origin where the storage event occurred.<br />

• Finally, the storageArea provides a convenient reference to the sessionStorage or<br />

localStorage where the value was changed. This gives the handler an easy way to<br />

query the storage for current values or make changes based on other storage<br />

changes.<br />

Listing 9-4 shows a simple event handler, which will raise an alert dialog with the contents of any<br />

storage event fired on the page’s origin.<br />

Listing 9-4. Event Handler that Displays Content of a Storage Event<br />

// display the contents of a storage event<br />

function displayStorageEvent(e) {<br />

var logged = "key:" + e.key + ", newValue:" + e.newValue + ", oldValue:" +<br />

e.oldValue +", url:" + e.url + ", storageArea:" + e.storageArea;<br />

alert(logged);<br />

}<br />

// add a storage event listener for this origin<br />

window.addEventListener("storage", displayStorageEvent, true);

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

Saved successfully!

Ooh no, something went wrong!