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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

CHAPTER 6 STORING DATA IN THE BROWSERThis statement creates a new local storage item, which I can read back using the same array-stylenotation, like this:viewModel.selectedItem(localStorage["selection"] || viewModel.items[0]);The effect of adding these two statements to the example is to create simple persistence <strong>for</strong> theuser’s selection. When the web app is loaded, I check to see whether there is data stored under theselection key and, if there is, set the corresponding data item in the view model, which restores theuser’s selection from an earlier session.• Tip It is important not to use local storage <strong>for</strong> sensitive in<strong>for</strong>mation or to trust the integrity of data retrievedfrom local storage <strong>for</strong> critical functions in your web app. Users can see and edit the contents of local storage,which means that nothing you store is secret and everything can be changed. Don’t store anything you don’t wantpublically disseminated, and don’t rely on local storage to give privileged access to your web app.From that point on, I update the value associated with the selection key each time my route ismatched by a URL change. I included a fallback to a default selection to cope with the possibility that thelocal storage data has been deleted (or this is the first time that the user has loaded the web app). To testthis feature, load the example web app, select one of the options, and then reload the web page. Thebrowser will reload the document, execute the <strong>JavaScript</strong> code afresh, and restore your selection.Storing JSON DataThe specification <strong>for</strong> local storage requires that keys and values are strings, just like in the previousexample. Being able to store a list of name/value pairs isn’t always that useful, but we can build on thesupport <strong>for</strong> strings to use local storage <strong>for</strong> JSON data, as shown in Listing 6-2.Listing 6-2. Using Local Storage <strong>for</strong> JSON Data...var viewModel = {selectedItem: ko.observable()};function loadViewModelData() {var storedData = localStorage["viewModelData"];if (storedData) {var storedDataObject = JSON.parse(storedData);viewModel.items = storedDataObject.items;viewModel.selectedItem(storedDataObject.selectedItem);} else {viewModel.items = ["Apple", "Orange", "Banana"];viewModel.selectedItem("Apple");}}139www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!