shopping cart knockout
by Leonardo Trimarchi
HTML
<h2>Your selected policies (<span data-bind="text: seats().length"></span>)</h2>
<table>
<thead><tr>
<th>Policy Holder name</th><th>Policy Type</th><th>Value</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 < 8">Add Policy for Redemption</button>
<h3 data-bind="visible: totalSurcharge() > 0">
Total value of Redemption: $<span data-bind="text: totalSurcharge().toFixed(2)"></span>
</h3>
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);
self.formattedPrice = ko.computed(function() {
var price = self.meal().price;
return price ? "$" + price.toFixed(2) : "None";
});
}
// 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: "MEDICARE SUPPLEMENT", price: 58.95 },
{ mealName: "LIFE INSURANCE", price: 34.95 },
{ mealName: "ACCIDENTAL AMPUTATION", price: 290 },
{ mealName: "PICKLE SLICING", price: 300 }
];
// Editable data
self.seats = ko.observableArray([
new SeatReservation("Johnny Knoxville", self.availableMeals[0]),
new SeatReservation("Evel Kneivel", self.availableMeals[0])
]);
// Computed data
self.totalSurcharge = ko.computed(function() {
var total = 0;
for (var i = 0; i < self.seats().length; i++)
total += self.seats()[i].meal().price;
return total;
});
// Operations
self.addSeat = function() {
self.seats.push(new SeatReservation("", self.availableMeals[0]));
}
self.removeSeat = function(seat) { self.seats.remove(seat) }
}
ko.applyBindings(new ReservationsViewModel());