JSFiddle - React, Tailwind, and code Playground
HTML
<p>
Cart 1
</p>
<table class = "shoppingcart">
</table>
<vr/>
<p>
Copy of cart 1
</p>
<table class = "shoppingcart">
</table>
JavaScript
class ShoppingCartHandler
{
constructor(uiElements)
{
this.uiElements = uiElements.toArray();
// Cartitems is an independent array from UI,
// but UI is updated when items are added here
this.cartItems = [];
}
addItem(name, price)
{
// Add item to the cartItems array
this.cartItems.push({ name: name, price: price });
// Update UI
this.render('ADD');
}
editItem(item, newName, newPrice)
{
this.cartItems[this.cartItems.findIndex(x => x.name === item)] = { name: newName, price: newPrice };
this.render('EDIT');
}
removeItem(name)
{
this.cartItems.splice(this.cartItems.findIndex(x => x.name === name), 1);
this.render('REMOVE');
}
render(renderAction)
{
switch(renderAction)
{
case 'ADD':
const lastCartItem = this.cartItems[this.cartItems.length - 1];
this.uiElements.forEach(elem =>
{
$(elem).append(`<tr><td>${lastCartItem.name}</td><td>${lastCartItem.price}</td></tr>`);
});
break;
case 'EDIT':
case 'REMOVE':
let appendString = '';
this.cartItems.forEach(item =>
{
appendString += `<tr><td>${item.name}</td><td>${item.price}</td></tr>`;
});
this.uiElements.forEach(elem =>
{
$(elem).empty();
$(elem).append(appendString);
});
break;
default:
break;
}
}
}
const cart = new ShoppingCartHandler($('.shoppingcart'));
// Don't have to worry about updating the UI when you add an item
cart.addItem('Banana', 10);
cart.addItem('Apple', 3);
cart.addItem('Beer', 12);
cart.removeItem('Apple');
cart.addItem('Orange', 6);
cart.editItem('Beer', 'Whiskey', 55);