user2471435
user2471435

Reputation: 1674

Trouble with foreach binding

I have a simple learning knockout program. I have used the foreach binding on an array and it just displays the header of the table with no datya binding. What's wrong?

<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head>
    <title>Hello Knockout.js</title>
    <script src="Scripts/knockout-2.3.0.js"></script> </head> <body>
    <h1>Hello Knockout.js</h1>
    <p><span data-bind='text: fullName'></span>'s Shopping Cart</p>

    <table>
        <thead><tr>
                   <th>Product</th>
                   <th>Price</th>
               </tr></thead>
        <tbody data-bind='foreach: shoppingCart'>
            <tr>
                <td data-bind='text: name'></td>
                <td data-bind='text: price'></td>
            </tr>
        </tbody>
    </table>

    <script type="text/javascript">
        function PersonViewModel() {
            this.firstName =  ko.observable("John");
            this.lastName = ko.observable("Smith");
            this.fullName = ko.computed(function() {
                return this.firstName() + " " + this.lastName();
            }, this);
        };

        function Product(name, price) {
            this.name = ko.observable(name);
            this.price = ko.observable(price);
        }

        var vm = new PersonViewModel();
        ko.applyBindings(vm);

        this.shoppingCart = ko.observableArray([            
            new Product['Beer', 10.99],
            new Product['Brats', 7.99],
            new Product['Buns', 1.49]
        ]);
            </script> </body> </html>

Upvotes: 0

Views: 75

Answers (1)

Sethcran
Sethcran

Reputation: 788

The observable shoppingCart doesn't exist in your viewModel at the time that you apply bindings to it. To fix this, adding shopping cart to your initial view model. If you want to update it later, you can.

See the JSFiddle

function PersonViewModel() {
    this.firstName =  ko.observable("John");
    this.lastName = ko.observable("Smith");
    this.fullName = ko.computed(function() {
        return this.firstName() + " " + this.lastName();
    }, this);

    this.shoppingCart = ko.observableArray([            
        new Product('Beer', 10.99),
        new Product('Brats', 7.99),
        new Product('Buns', 1.49)
    ]);
};

function Product(name, price) {
    this.name = ko.observable(name);
    this.price = ko.observable(price);
}

var vm = new PersonViewModel();
ko.applyBindings(vm);

Upvotes: 1

Related Questions