JSFiddle - React, Tailwind, and code Playground
HTML
<div id="ServiceContainer">
<p>Id: <strong data-bind="text: ServiceId"></strong></p>
<p>Description: <strong data-bind="text: Description"></strong></p>
<p>Id: <input data-bind="value: ServiceId" /></p>
<p>Description: <input data-bind="value: Description" /></p>
<p>Full name: <strong data-bind="text: fullName"></strong></p>
<button data-bind="click: capitaliseDescription">Go caps</button>
<button data-bind="click: unCapitaliseDescription">Go un-caps</button>
</div>
<div id="ReservationsContainer">
<h2>Your seat reservations</h2>
<table>
<thead><tr>
<th>Passenger name</th><th>Meal</th><th>Surcharge</th><th></th>
</tr></thead>
<!-- Todo: Generate table body -->
<tbody data-bind="foreach: seats">
<tr>
<td data-bind="text: name"></td>
<td data-bind="text: meal().mealName"></td>
<td data-bind="text: meal().price"></td>
</tr>
</tbody>
</table>
</div>
JavaScript
// This is a simple *viewmodel* - JavaScript that defines the data and behavior of your UI
function ServiceViewModel() {
this.ServiceId = ko.observable(1);
this.Description = ko.observable("Pedicure");
this.fullName = ko.computed(function() {
return this.ServiceId() + " : " + this.Description();
}, this);
this.capitaliseDescription = function() {
var currentVal = this.Description();
this.Description(currentVal.toUpperCase());
};
this.unCapitaliseDescription = function() {
var currentVal = this.Description();
this.Description(currentVal.toLowerCase());
};
}
// Activates knockout.js
ko.applyBindings(new ServiceViewModel(), document.getElementById("ServiceContainer"));
/*** Working with Lists and Collections ***/
// 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[1])
]);
}
ko.applyBindings(new ReservationsViewModel(), document.getElementById("ReservationsContainer"));