Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to use loading and saving data from the local storage

    • 0
    • 1
    • 1
    • 1
    • 0
    • 0
    • 0
    • 0
    • 393
    Comment on it

    In below code, I have used a constructor shoppingCart for the parameter CartName which identifies the Cart while loading data from the local storage. I have also used clearItems() function which is used to clear the cart and saveItems which is used for saving data items.

    function shoppingCart(CartName) {
        this.cartName = cartName;
        this.clearCart = false;
        this.checkoutParameters = {};
        this.items = [];
        this.loadItems();
        var self = this;
        $(window).unload(function () {
            if (self.clearCart) {
                self.clearItems();
            }
            self.saveItems();
            self.clearCart = false;
        });
    }
    
    shoppingCart.prototype.loadItems = function () {
        var items = localStorage != null ? localStorage[this.CartName + "_items"] : null;
        if (items != null && JSON != null) {
            try {
                var items = JSON.parse(items);
                for (var i = 0; i < items.length; i++) {
                    var item = items[i];
                    if (item.sku != null && item.name != null && item.price != null && item.quantity != null) {
                        item = new CartItem(item.sku, item.name, item.price, item.quantity);
                        this.items.push(item);
                    }
                }
            }
            catch (err) {
                // catches the errors while loading 
            }
        }
    }
    shoppingCart.prototype.saveItems = function () {
        if (localStorage != null && JSON != null) {
            localStorage[this.cartName + "_items"] = JSON.stringify(this.items);
        }
    }
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: