foreach绑定麻烦

时间:2013-07-25 18:19:05

标签: knockout.js

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

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

1 个答案:

答案 0 :(得分: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);