12.07.2015 Views

Pro JavaScript for Web Apps pdf - EBook Free Download

Pro JavaScript for Web Apps pdf - EBook Free Download

Pro JavaScript for Web Apps pdf - EBook Free Download

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.

CHAPTER 6 STORING DATA IN THE BROWSERI have used the same keys <strong>for</strong> the persistentObservable function when defining the view model andadded an iframe element that embeds the other HTML document. Since both are loaded from the sameorigin, the browser shares the same local storage between them. Changing the value of an input elementin one document will trigger a corresponding change in the other document, via local storage and thetwo view models.• Caution The browsers don’t provide any guarantees about the integrity of a data item if updates are written tolocal storage from two documents simultaneously. It is hard to cater <strong>for</strong> this eventuality (and I have never seen ithappen), but it is prudent to assume that data corruption can occur if you are sharing local storage.Using Session StorageThe complement to local storage is session storage, which is accessed through the sessionStorage object.The sessionStorage and localStorage objects are used in the same way and emit the same storageevent. The difference is that the data is deleted when the document is closed in the browser (morespecifically, the data is deleted when the top-level browsing context is destroyed, but that’s usually thesame thing).The most common use <strong>for</strong> session storage is to preserve data when a document is reloaded. This is auseful technique, although I have to admit that I tend to use local storage to achieve the same effectinstead. The main benefit of session storage is per<strong>for</strong>mance, since the data is usually held in memoryand doesn’t need to be written to disk. That said, if you care about the marginal per<strong>for</strong>mance gains thatthis offers, then you may need to consider whether the browser is the best environment <strong>for</strong> your app.Listing 6-7 shows how I have added support <strong>for</strong> session persistence to my observable data item inutils.js.Listing 6-7. Defining a Semi-persistent Observable Data Item Using Session Storageko.persistentObservable = function(keyName, initialValue, useSession) {var storageObject = useSession ? sessionStorage : localStoragevar obItem = ko.observable(storageObject[keyName] || initialValue);148www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!