How to do Foreach Binding using knockout js
Posted By Rajan Rawat | 12-Dec-2016
In the next few minutes you'll build a dynamic UI for reserving seats and meals — this could be one step in an airline booking process. In the bottom-right pane, you've already got:
ReservationsViewModel, a viewmodel class that holds:
seats, an array holding an collection of SeatReservation instances. Note that it's a ko.observableArray - not surprisingly, that's the observable equivalent of a regular array, THAT means it can automatically trigger UI update whenever item are added or removed from the list.
The view (top-right pane) doesn't yet display the reservation data, so let's fix that. Update the <tbody> element to use the foreach binding, so that it will render a copy of its child elements for each entry in the seats array:
Notice that, because the meal property is an observable, it's important to invoke meal as a function (to obtain the current value) before attempting it to read sub-properties. In other words, write meal().price, not meal.price.
The result? If you run the application now, you should see a simple table of seat reservation information.
foreach is part of a family of control flow bindings that includes foreach, if, ifnot, and with. That make it these things possible to construct any kind of iterative or conditional or nested UI based on a dynamic viewmodel.
<tr><th>First name</th><th>Last name</th></tr>