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 BROWSERwindow.applicationCache.swapCache();window.location.reload(false);}});} else {createDialog("Try again later");}});});This is a simple change, and you’ll quickly realize that I am doing some mild misdirection. When thebrowser is online, the user can submit the <strong>for</strong>m as normal, and any data in local storage is cleared. Themisdirection comes when the browser is offline and the user clicks the Save <strong>for</strong> Later button. All I do iscall the createDialog function, telling the user that the <strong>for</strong>m data has been saved. However, I don’tactually need to save the data because I am using persistent observable data items in the view model.The user doesn’t need to know about this; they just get the benefit of the persistence and a clear signalfrom the web application that the <strong>for</strong>m data has not been submitted. When the browser is online again,the user can submit the data. Using local storage all of the time means that the user won’t lose their dataif they close and later reload the application be<strong>for</strong>e being able to submit the <strong>for</strong>m to the server. Forcompleteness, Listing 6-13 shows the createDialog function, which I defined in the utils.js file. This isthe same approach I used to create an error dialog in the original example, and I moved the code into afunction because I needed to create the same kind of dialog box at multiple points in the application.Listing 6-13. The createDialog Functionfunction createDialog(message) {$('' + message + '').dialog({modal: true,title: "Message",buttons: [{text: "OK",click: function() {$(this).dialog("close")}}]});};I have taken a very simple and direct approach to dealing with <strong>for</strong>m data when the browser isoffline, but you can easily see how a more sophisticated approach could be created. You might, <strong>for</strong>example, respond to the online event by prompting the user to submit the data or even submit itautomatically using Ajax. Whatever approach you take, you must ensure that the user understands andapproves of what your web app is doing.Storing Complex DataStoring name/value pairs is perfectly suited to storing <strong>for</strong>m data, but <strong>for</strong> anything more sophisticated,such a simple approach starts to break down. There is another browser feature, called IndexedDB, whichyou can use to store and work with more complex data.156www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!