1
我有一些可觀察的數組項(簡單的數字對),我想將它綁定到一個表。然後我想綁定一個循環第一個數組的計算的observable,並通過分組彙總一些值。我的foreach循環工作正常,並按羣組總結數字(正如你可以通過取消註釋我的警報一樣),但它永遠不會綁定到html。看下面我的小提琴。我哪裏錯了?我可以綁定到計算的observable數組(敲除)嗎?
function DataPoint(group, num) {
this.group = group;
this.num = num;
}
function TestViewModel() {
var self = this;
self.data = ko.observableArray([
new DataPoint(1, 1),
new DataPoint(2, 5),
new DataPoint(3, 9),
new DataPoint(3, 10),
new DataPoint(4, 3),
new DataPoint(4, 6),
new DataPoint(5, 3),
new DataPoint(5, 9),
new DataPoint(6, 7),
new DataPoint(7, 2),
new DataPoint(8, 8),
new DataPoint(8, 4),
new DataPoint(9, 3),
new DataPoint(11, 6)
])
self.groupedData = ko.computed(function() {
var total = 0;
var group = -1;
var myArray = self.data();
var counter = 0;
var rows = self.data().length;
var result = ko.observableArray([]);
ko.utils.arrayForEach(myArray, function (item) {
if (group == -1) {
group = item.group;
}
if (group == item.group) {
total += parseInt(item.num)
} else {
var d = new DataPoint(group, total);
result.pop(d);
total = 0;
group = item.group;
total += parseInt(item.num)
//alert(d.group + ':' + d.num);
}
if (counter == rows - 1) {
var d = new DataPoint(group, total);
result.pop(d);
//alert(d.group + ':' + d.num);
}
counter += 1;
});
return result();
},self);
}
ko.applyBindings(new TestViewModel());
和HTML
<body>
Ungrouped Data
<table>
<thead>
<tr>
<td>Group</td>
<td>Sum</td>
</tr>
</thead>
<tbody data-bind="foreach: data">
<tr>
<td>
<span data-bind="text: group"></span>
</td>
<td>
<span data-bind="text: num"></span>
</td>
</tr>
</tbody>
</table>
<br />
Grouped Data
<table>
<thead>
<tr>
<td>Group</td>
<td>Sum</td>
</tr>
</thead>
<tbody data-bind="foreach: groupedData">
<tr>
<td>
<span data-bind="text: group"></span>
</td>
<td>
<span data-bind="text: num"></span>
</td>
</tr>
</tbody>
</table>
<script src="Scripts/lib/knockout-3.0.0.js"></script>
<script src="Scripts/app/TestViewModel.js"></script>
</body>
http://jsfiddle.net/gaku6mku/1/
預先感謝任何建議!
的兒子.....非常感謝!我知道它必須是簡單的東西,但是我迷失在我想做的事情中。當我簡化我的視圖模型以創建此示例時,我應該注意到它。 – 2014-09-05 13:49:11
此外,您很少需要在計算的可觀察值內創建觀測值。 'var result = ko.observableArray([]);'應該是'var result = [];' – 2014-09-05 22:18:59