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 BROWSERfunction storeViewModelData() {var viewModelData = {items: viewModel.items,selectedItem: viewModel.selectedItem()};localStorage["viewModelData"] = JSON.stringify(viewModelData);}$(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();});});...I have defined two new functions in the script element to support storing JSON. ThestoreViewModelData function is called whenever the user makes a selection. JSON is only able to storedata values and not <strong>JavaScript</strong> functions, so I extract the data values from the view model and use themto create a new object. I pass this object to the JSON.stringify method, which returns a JSON string, likethis:{"items":["Apple","Orange","Banana"],"selectedItem":"Banana"}I store this string by associating it with the viewModelData key in local storage. The correspondingfunction is loadViewModelData. I call this function when the jQuery ready event is fired and use it tocomplete the view model.• Tip The persistent nature of local storage means that if you reuse a key to store a different kind of data, yourun the risk of encountering the old <strong>for</strong>mat that was stored in a previous session. The simplest way to handle thisin development is to clear the browser’s cache. In production, you must be able to detect the old data and eitherprocess it or, at the very least, be able to discard it without generating any errors.140www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!