JSFiddle - React, Tailwind, and code Playground

by Jon Kittell

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.3.0/knockout-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<p><span data-bind='text: fullName'></span>'s Shopping Cart</p>
<table>
    <thead><tr>
        <th>Product</th>
        <th>Price</th>
        </tr></thead>
    <tbody data-bind='foreach: shoppingCart'>
        <tr>
            <td data-bind='text: name'></td>
            <td data-bind='text: price'></td>
            <td><button data-bind='click: $root.removeProduct'>Remove</button></td>
        </tr>
    </tbody>
</table>

<button data-bind='click: addProduct'>Add</button>

<button data-bind='click: checkout'>Checkout</button>

JavaScript

function Product(name, price) {
        this.name = ko.observable(name);
        this.price = ko.observable(price);
    }
    
function vm() {
    var self = this;
    this.firstName = ko.observable("John");
    this.lastName = ko.observable("Smith");
    self.fullName = ko.computed(function() {
        return this.firstName() + " " + this.lastName();
    }, this);
    this.shoppingCart = ko.observableArray([
        new Product("Beer", 10.99),
        new Product("Brats", 7.99),
        new Product("Buns", 1.49)
    ]);
    this.addProduct = function() {
        this.shoppingCart.push(new Product("More Beer", 10.99));
    };
    this.removeProduct = function(product) {
        self.shoppingCart.destroy(product);
        alert(self.shoppingCart().length);
    };
    this.checkout = function() {
        alert("Checking out");
    };
}

ko.applyBindings(new vm());