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)