2014-09-23 100 views
0

我是Knockout的新手,有一個問題: 我嘗試this來自officail站點的示例。Knockout asp.net - 無法讀取undefined的屬性

所以我的HTML文件:

<head> 
    <script src="Scripts/jquery-2.1.1.min.js"></script> 
    <script src="Scripts/knockout-3.2.0.js"></script> 
</head> 
<body> 
     <div data-bind='simpleGrid: gridViewModel'> </div> 

     <button data-bind='click: addItem'> 
      Add item 
     </button> 

     <button data-bind='click: sortByName'> 
      Sort by name 
     </button> 

     <button data-bind='click: jumpToFirstPage, enable: gridViewModel.currentPageIndex'> 
      Jump to first page 
     </button> 
    <script src="FuseJS.js"></script> 
</body> 
</html> 

和我的js文件是:

/// <reference path="Scripts/jquery-2.1.1.min.js" /> 
/// <reference path="Scripts/knockout-3.2.0.js" /> 
var initialData = [ 
    { name: "Well-Travelled Kitten", sales: 352, price: 75.95 }, 
    { name: "Speedy Coyote", sales: 89, price: 190.00 }, 
]; 

var PagedGridModel = function (items) { 
    this.items = ko.observableArray(items); 

    this.addItem = function() { 
     this.items.push({ name: "New item", sales: 0, price: 100 }); 
    }; 

    this.sortByName = function() { 
     this.items.sort(function (a, b) { 
      return a.name < b.name ? -1 : 1; 
     }); 
    }; 

    this.jumpToFirstPage = function() { 
     this.gridViewModel.currentPageIndex(0); 
    }; 

    this.gridViewModel = new ko.simpleGrid.viewModel({ 
     data: this.items, 
     columns: [ 
      { headerText: "Item Name", rowText: "name" }, 
      { headerText: "Sales Count", rowText: "sales" }, 
      { headerText: "Price", rowText: function (item) { return "$" + item.price.toFixed(2) } } 
     ], 
     pageSize: 4 
    }); 
}; 

ko.applyBindings(new PagedGridModel(initialData)); 

我缺少什麼?我調試我看到這個錯誤的代碼 「UncauchType錯誤:無法讀取屬性'viewModel'undefined」 tnx

+3

可能重複[請問simpleGrid需要額外下載?](http://stackoverflow.com/questions/18507885/does-the-simplegrid-require-additional-downloads) – Nathan 2014-09-23 13:15:52

+0

感謝!其作品! – zvi 2014-09-23 13:19:45

回答

0

您沒有在任何地方使用ko.applyBindings()。

理想情況下,你需要做這樣的事情。

ko.applyBindings(new PagedGridModel(initialData)); 
+1

我從他的問題的最後一行復制了'ko.applyBindings(new PagedGridModel(initialData));'。 – edhedges 2014-09-23 13:55:23

+0

是的,我錯過了,謝謝你的擡頭 – QBM5 2014-09-23 13:56:21