JSFiddle - React, Tailwind, and code Playground
by Igor Cuckovic
HTML
<h2>Your seat reservations (<span data-bind="text: seats().length"></span>)</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><select data-bind="options: $root.availableMeals, value: meal, optionsText: 'mealName'"></select></td>
<td data-bind="text: formattedPrice"></td>
<td><a href="#" data-bind="click: $root.removeSeat">Remove</a></td>
</tr>
</tbody>
</table>
<button data-bind="click: addSeat, enable: seats().length < 5">Reserve another seat</button>
<h3 data-bind="visible: totalSurcharge() > 0">
Total surcharge: $<span data-bind="text: totalSurcharge().toFixed(2)"></span>
</h3>
JavaScript
function SeatReservation(name, initialMeal) {
var meal = ko.observable(initialMeal);
return {
name: name,
meal: ko.observable(initialMeal),
formattedPrice: ko.computed(function() {
var price = meal().price;
return price ? "$" + price.toFixed(2) : "None";
})
}
}
// Overall viewmodel for this screen, along with initial state
function ReservationsViewModel() {
// Non-editable catalog data - would come from the server
var availableMeals = [
{ mealName: "Standard (sandwich)", price: 0 },
{ mealName: "Premium (lobster)", price: 34.95 },
{ mealName: "Ultimate (whole zebra)", price: 290 }
];
// Editable data
var seats = ko.observableArray([
SeatReservation("Steve", availableMeals[0]),
SeatReservation("Bert", availableMeals[0])
]);
// Operations
var addSeat = function() {
seats.push(new SeatReservation("", availableMeals[0]));
}
var removeSeat = function(seat) { seats.remove(seat) }
var totalSurcharge = ko.computed(function() {
return seats().reduce(function (acc, cur) {
return acc + cur.meal().price
},0)
});
return {
availableMeals: availableMeals,
seats: seats,
addSeat: addSeat,
removeSeat: removeSeat,
totalSurcharge :totalSurcharge
}
}
ko.applyBindings(ReservationsViewModel());