KnockoutJS - 显示每个项目的累积值

时间:2017-06-07 11:59:49

标签: javascript knockout.js

如何在表格中显示带有KnockoutJS的observableArray中每个项目的累积值?

我需要一些像:

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 个答案:

答案 0 :(得分:1)

我不确定你想要第三列的价值,但主要方法仍然是相同的:

  • 让您的Item班级访问他们的&#34;兄弟项目&#34;通过传递对数组的引用
  • 在计算属性中,做一个&#34;看后面&#34;通过查找项目自己的索引。
  • 在两个(或更多)Item个实例之间执行某种计算并返回值

例如,此acc属性返回先前acc的{​​{1}}和自己的Item属性:

&#13;
&#13;
note
&#13;
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());
&#13;
&#13;
&#13;