2013-07-25 79 views
0

我有一個簡單的學習挖空程序。我已經在數組上使用了foreach綁定,它只是顯示沒有datya綁定的表頭。怎麼了?與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> 

回答

1

在您應用綁定到viewModel時,observable shoppingCart不存在於您的viewModel中。要解決此問題,請將購物車添加到初始視圖模型。如果你想稍後更新它,你可以。

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); 
+0

這仍然不是我 – user2471435

+0

增加了的jsfiddle工作。 ko.observableArray中有一些語法錯誤 – Sethcran