我正在尝试将文本框中的值提交到一个数组中,该数组将以表格格式显示。将进行进一步的计算,但现在我遇到了绑定问题。在 chrome 的控制台中,我得到的错误是
Uncaught TypeError: Property 'item' of object#<ItemEntry> is not a function
我不知道应该在哪里定义 newItem (从文本框提交的值)。
这是HTML
<td><input type="text" data-bind="value: newItem" /></td>
<button data-bind="click: addItem">Add Item</button>
<table>
<thead><tr>
<th>Item Number</th><th>Price</th><th></th>
</tr></thead>
<tbody data-bind="foreach: itemNumbers">
<tr>
<td data-bind="text: item"></td>
<td data-bind="text: price"></td>
<td><a href="#" data-bind="click: $root.removeItem">Remove</a></td>
</tr>
</tbody>
</table>
<h3 data-bind="visible: totalCost() > 0">
Total Cost: $<span data-bind="text: totalCost().toFixed(2)"></span>
</h3>
这是javascript
function ItemEntry(item, price) {
var self = this;
self.item = item;
self.price = price;
}
// Overall viewmodel for this screen, along with initial state
function EntryViewModel(newItem) {
var self = this;
self.newItem = newItem;
// Editable data
self.itemNumbers = ko.observableArray([
new ItemEntry("New Item", "$22.50")
]);
// Computed data
self.totalCost = ko.computed(function() {
var total = 0;
for (var i = 0; i < self.itemNumbers().length; i++)
total += self.itemNumbers()[i].item.price;
return total;
});
// Operations
self.addItem = function() {
self.itemNumbers.push(new ItemEntry(self.newItem, "$20.00"));
}
self.removeItem = function(item) { self.itemNumbers.remove(item) }
}
ko.applyBindings(new EntryViewModel());