到目前为止,我还未能找到解决此问题的方案。我正在尝试在主列表中更改数量框时填充汇总表。这是我目前的代码:
<div class="mainItems">
<ul data-bind="foreach: finalListItems">
<li> <input class="qty" data-bind="value: qty, valueUpdate: 'afterkeydown'" size="4"/><label data-bind="text: item" ></label></li>
</ul>
</div>
<div>
<table>
<thead>
<tr>
<th>Item</th>
<th>Quantity</th>
</tr>
</thead>
<tbody data-bind="foreach: finalListItems">
<tr>
<td data-bind="text: item"></td>
<td data-bind="text: qty"></td>
</tr>
</tbody>
</table>
</div>
ViewBox:
function sortedListItem(qty, listItemName) {
var self = this;
self.qty = ko.observable(qty);
self.item = listItemName;
}
var trialViewModel = function(){
var self = this;
self.availableListItems = [
{itemName: "Here is Item 1"},
{itemName: "Here is Item 2"},
{itemName: "Here is Item 3"},
{itemName: "Here is Item 4"},
{itemName: "Here is Item 5"}
];
self.finalListItems = ko.observableArray([
new sortedListItem(ko.observable.qty, self.availableListItems[0].itemName),
new sortedListItem(ko.observable.qty, self.availableListItems[1].itemName),
new sortedListItem(ko.observable.qty, self.availableListItems[2].itemName),
new sortedListItem(ko.observable.qty, self.availableListItems[3].itemName),
new sortedListItem(ko.observable.qty, self.availableListItems[4].itemName)
]);
};
ko.applyBindings(trialViewModel());
我在这里也包含了一个JSFiddle,所以你可以看到我想要的想法:
问题是如果更改了数量框,我只希望项目在摘要中可见。我无法将可见性绑定绑定到数组中的单个项目,我还没有看到任何类似的东西。有什么建议吗?
答案 0 :(得分:0)
有几种方法可以做到这一点,但这里有一个更新的小提琴,可能会让你开始走上一条道路:http://jsfiddle.net/RYmf7/1/
我们的想法是为每个项目的模型添加isVisible
属性,并将其用于可见的数据绑定。
//model for the sortedListItem
function sortedListItem(qty, listItemName) {
var self = this;
self.qty = ko.observable(qty);
self.item = listItemName;
self.isVisible = ko.computed(function(){
return self.qty() !== 0;
});
}
答案 1 :(得分:0)
您可以在更改值时将每个项目标记为脏。将根据哪些项目具有新数量来构建摘要列表。
function sortedListItem(qty, listItemName) {
var self = this;
self.originalqty = qty;
self.qty = ko.observable(qty);
self.item = listItemName;
self.isDirty = ko.computed(function() {
return self.originalqty != self.qty();
}, this);
}
var trialViewModel = function(){
var self = this;
self.availableListItems = [
{itemName: "Here is Item 1"},
{itemName: "Here is Item 2"},
{itemName: "Here is Item 3"},
{itemName: "Here is Item 4"},
{itemName: "Here is Item 5"}
];
self.finalListItems = ko.observableArray([
new sortedListItem(ko.observable.qty, self.availableListItems[0].itemName),
new sortedListItem(ko.observable.qty, self.availableListItems[1].itemName),
new sortedListItem(ko.observable.qty, self.availableListItems[2].itemName),
new sortedListItem(ko.observable.qty, self.availableListItems[3].itemName),
new sortedListItem(ko.observable.qty, self.availableListItems[4].itemName)
]);
self.summaryListItems = ko.computed(function() {
var summaryItems = [];
ko.utils.arrayForEach(self.finalListItems(), function(item) {
if (item.isDirty()) {
summaryItems.push(item);
}
});
return summaryItems;
});
};
ko.applyBindings(trialViewModel());