2017-06-07 15 views
1

如何使用KnockoutJS在一個表中顯示observableArray中每個項目的累計值?KnockoutJS - 顯示每個項目的累計值

我需要事端,如:

function ViewModel(){ 
 
var self = this; 
 

 
self.Item = function(day,note){ 
 
this.day = ko.observable(day); 
 
this.note = ko.observable(note); 
 
}; 
 
} 
 

 

 
var itemsFromServer = [ 
 
{day:'Mo', note:1}, 
 
{day:'Tu', note:2}, 
 
{day:'We', note:3}, 
 
{day:'Th', note:4}, 
 
{day:'Fr', note:5}, 
 
{day:'Su', note:6}, 
 
]; 
 

 
var vm = new ViewModel(); 
 

 
var arrItems = ko.utils.arrayMap(itemsFromServer, function(item) { 
 
    return new vm.Item(item.day, item.note); 
 
    }); 
 
    
 
ko.applyBindings(vm);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script> 
 

 
<table> 
 
    <thead> 
 
     <tr><th>Day</th><th>Note</th><th>Accumulate</th></tr> 
 
    </thead> 
 
    <tbody data-bind="foreach: arrItems"> 
 
     <tr> 
 
      <td data-bind="text: day"></td> 
 
      <td data-bind="text: note"></td> 
 
      <td >the currente 'note' + the anterior 'note'</td> 
 
     </tr> 
 
    </tbody> 
 
</table>

最後一欄應該顯示當前項目+前項的總和。 謝謝。

回答

1

我不能完全確定要在第三列是什麼價值,但主要的方法是一樣的:

  • 傳遞一個參考給你Item類訪問它們的「兄弟項目」數組
  • 在計算屬性中,通過查找項目自己的索引來執行「查看後面」。
  • 執行某種計算的兩個(或更多)之間Item實例和返回值

例如,這acc屬性返回以前Itemacc和那些擁有note屬性:

var Item = function(day, note, siblings){ 
 
    this.day = ko.observable(day); 
 
    this.note = ko.observable(note); 
 

 
    this.acc = ko.pureComputed(function() { 
 
    var allItems = siblings(); 
 
    var myIndex = allItems.indexOf(this); 
 
    
 
    var base = myIndex > 0 
 
     ? allItems[myIndex - 1].acc() 
 
     : 0 
 
    
 
    return base + this.note(); 
 
    }, this); 
 
}; 
 

 
function ViewModel() { 
 
    var self = this; 
 

 
    self.items = ko.observableArray([]); 
 
    
 
    self.items(itemsFromServer.map(function(item) { 
 
     return new Item(item.day, item.note, self.items); 
 
    }) 
 
); 
 
} 
 

 

 
var itemsFromServer = [ 
 
    {day:'Mo', note:1}, 
 
    {day:'Tu', note:2}, 
 
    {day:'We', note:3}, 
 
    {day:'Th', note:4}, 
 
    {day:'Fr', note:5}, 
 
    {day:'Su', note:6}, 
 
]; 
 

 
ko.applyBindings(new ViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script> 
 

 
<table> 
 
    <thead> 
 
    <tr> 
 
     <th>Day</th> 
 
     <th>Note</th> 
 
     <th>Accumulate</th> 
 
    </tr> 
 
    </thead> 
 
    <tbody data-bind="foreach: items"> 
 
    <tr> 
 
     <td data-bind="text: day"></td> 
 
     <td data-bind="text: note"></td> 
 
     <td data-bind="text: acc"></td> 
 
    </tr> 
 
    </tbody> 
 
</table>

+0

這正是我要找的。謝謝 –