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 BROWSERI load the JSON string and use the JSON.parse method to create a <strong>JavaScript</strong> object if there is localstorage data associated with the viewModelData key. I can then read the properties of the object topopulate the view model. Of course, I cannot rely on there being data available, so I fall back to somesensible default values if needed.STORING OBJECT DATAIt wasn’t hard to separate the data from the object that contained it in my simple example, but it can besignificantly more difficult in a complex web application. You might be tempted to shortcut this process bystoring objects directly, rather than mapping data to strings. Don’t do this; it will only cause you problems.Here is a code snippet that shows local storage being used with objects:...var viewModel = {};function loadViewModelData() {var storedData = localStorage["viewModelData"];if (storedData) {viewModel = storedData;} else {viewModel.items = ["Apple", "Orange", "Banana"];viewModel.selectedItem = ko.observable("Apple");}}function storeViewModelData() {localStorage["viewModelData"] = viewModel;}$(document).ready(function() {loadViewModelData();ko.applyBindings(viewModel);$('div.catSelectors').buttonset();hasher.initialized.add(crossroads.parse, crossroads);hasher.changed.add(crossroads.parse, crossroads);hasher.init();crossroads.addRoute("select/{item}", function(item) {viewModel.selectedItem(item);storeViewModelData();});});...141www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!