JSFiddle - React, Tailwind, and code Playground

by danielwertheim

HTML

<script src="http://cloud.github.com/downloads/SteveSanderson/knockout/knockout-2.0.0.js"></script>
<h2>Your seat reservations</h2>
<table>
    <thead>
        <tr>
            <th>Passenger name</th>
            <th>Meal</th>
            <th>Surcharge</th>
            <th></th>
        </tr>
    </thead>
    <tbody data-bind="foreach: seats">
        <tr>
            <td><input data-bind="value: name" /></td>
            <td>
                <label data-bind="text: meal().mealName, attr:{for: $root.seats.ctrlId($data)}"></label>
                <select data-bind="options: $root.availableMeals, value: meal, optionsText: 'mealName', attr:{id: $root.seats.ctrlId($data)}"></select>
            </td>
            <td data-bind="text: $data.meal().price"></td>
            <td></td>
        </tr>
    </tbody>
</table>

JavaScript

// Class to represent a row in the seat reservations grid
function SeatReservation(name, initialMeal) {
    var self = this;
    self.name = name;
    self.meal = ko.observable(initialMeal);
}

// Overall viewmodel for this screen, along with initial state
function ReservationsViewModel() {
    var self = this;

    // Non-editable catalog data - would come from the server
    self.availableMeals = [
        { mealName: "Standard (sandwich)", price: 0 },
        { mealName: "Premium (lobster)", price: 34.95 },
        { mealName: "Ultimate (whole zebra)", price: 290 }
    ];    

    // Editable data
    self.seats = ko.observableArray([
        new SeatReservation("Steve", self.availableMeals[0]),
        new SeatReservation("Bert", self.availableMeals[0])
    ]);
    
    self.seats.ctrlId = function(seat) {return 'meal_' + self.seats.indexOf(seat);};
    
    self.addSeat = function() {
      self.seats.push(new SeatReservation("", self.availableMeals[0]));  
    };
}

ko.applyBindings(new ReservationsViewModel());