Blog

  • FOREACH BINDING

    Getting started

    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:

    SeatReservation, a simple JavaScript class constructor that stores a passenger name with a meal selection
    ReservationsViewModel, a viewmodel class that holds:
    availableMeals, a JavaScript object that provides the meal data
    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.

     

    HTML CODE

    <table>
        <thead>
            <tr><th>First name</th><th>Last name</th></tr>
        </thead>
        <tbody data-bind="foreach: people">
            <tr>
                <td data-bind="text: firstName"></td>
                <td data-bind="text: lastName"></td>
            </tr>
        </tbody>
    </table>
     
    <script type="text/javascript">
        ko.applyBindings({
            people: [
                { firstName: 'Bert', lastName: 'Bertington' },
                { firstName: 'Charles', lastName: 'Charlesforth' },
                { firstName: 'Denise', lastName: 'Dentiste' }
            ]
        });
    </script>

     

    OUTPUT

    People

    • Name at position 0Bert Remove
    • Name at position 1Charles Remove
    • Name at position 2Denise Remove

Tags: Knockoutjs