0

我有一个简单的学习淘汰计划。我在数组上使用了 foreach 绑定,它只显示表的标题,没有数据绑定。怎么了?

<!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>
4

1 回答 1

1

在您对其应用绑定时,您的 viewModel 中不存在可观察的 shoppingCart。要解决此问题,请将购物车添加到您的初始视图模型中。如果你想稍后更新它,你可以。

请参阅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);
于 2013-07-25T18:30:10.560 回答