LocalStorage Test

by Jimmy Chandra

JavaScript

$(function() {
    var invoice, jsonData, serverLoad = false;
    
    window.ViewBag = window.ViewBag || {};
    ViewBag.invoiceId = 'ABC123';

    //pretend old data is in localStorage...
    if (window.localStorage) {
        console.log('Saving invoice data to localStorage');
        window.localStorage['tempInvoice'] = JSON.stringify({
            InvoiceId : 'ABC123',
            Data : 'GAABOOGAA'
        });
    }
    
    //load from localStorage
    if (window.localStorage) {
        console.log('Trying to load tempInvoice from localStorage');
        jsonData = window.localStorage['tempInvoice'];
    }
    
    //found
    if (typeof jsonData !== 'undefined') {
        console.log('tempInvoice found in localStorage');
        invoice = JSON.parse(jsonData);
            
        if (invoice.InvoiceId !== ViewBag.invoiceId) {
            console.log('existing tempInvoice does not match current invoice Id');
            if (window.localStorage) {
                console.log('Removing tempInvoice from localStorage');
                window.localStorage.removeItem('tempInvoice');
            }
            
            serverLoad = true;
        } else {
            serverLoad = !confirm('A local copy of the invoice data is found on your machine.  Click OK to use it.  Click Cancel to load the data from server.');            
        }            
    } else {
        console.log('tempInvoice is not found in localStorage');
        serverLoad = true;
    }
    
    if (serverLoad) {
        console.log('Loading invoice ABC123 from server...');
        //simulate load invoice from server...
        invoice = {
            InvoiceId : 'ABC123',
            Data : 'BOOGABOO'
        }
    } else {
        console.log('Using existing invoice ABC123');
    }
});