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 BROWSER $()($)Total:$In this listing, I use the JSON.stringify method to store a copy of the view model data when the Ajaxrequest is successful:$.getJSON("products.json", function(data) {cheeseModel.products = data;localStorage["jsondata"] = JSON.stringify(data);})I added the products.json URL to the NETWORK section of the manifest <strong>for</strong> this web app, so I have areasonable expectation that the data will be available and that the Ajax request will succeed.If, however, the request fails, which will definitely happen if the browser is offline, then I try tolocate and restore the serialized data from local storage, like this:}).error(function() {if (localStorage["jsondata"]) {cheeseModel.products = JSON.parse(localStorage["jsondata"]);}})Assuming the initial request works, I will have a good fallback position if subsequent requests fail.The effect that this technique creates is similar to the way that Firefox handles Ajax requests when thebrowser is offline because I end up using the last version of the data I was able to obtain from the server.152www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!