我正在http://learn.knockoutjs.com/#/?tutorial=collections的knockoutjs教程中,我丢失了我的可迭代项目foreach: seats
。首先,我的观点看起来像:
<h2>Your seat reservations</h2>
<table>
<thead>
<tr>
<th>Passenger name</th><th>Meal</th><th>Surcharge</th><th></th>
</tr>
</thead>
<!-- Todo: Generate table body -->
<tbody data-bind="foreach: seats">
<tr>
<td><input data-bind="value: name"/></td>
<td><select data-bind="options: $root.availableMeals, value: meal, optionsText: 'mealName'"></select></td>
<td data-bind="text: meal().price"></td>
</tr>
</tbody>
</table>
<button data-bind="click: addSeat">Reserve another seat</button>
得到了
现在我有了
视图
<h2>Your seat reservations</h2>
<table>
<thead>
<tr>
<th>Passenger name</th><th>Meal</th><th>Surcharge</th><th></th>
</tr>
</thead>
<!-- Todo: Generate table body -->
<tbody data-bind="foreach: seats">
<tr>
<td><input data-bind="value: name"/></td>
<td><select data-bind="options: $root.availableMeals, value: meal, optionsText: 'mealName'"></select></td>
<td><select data-bind="options: $root.availableMeals, value: price, optionsText: 'price'"></select></td>
</tr>
</tbody>
</table>
<button data-bind="click: addSeat">Reserve another seat</button>
VM未更改
// Class to represent a row in the seat reservations grid
function SeatReservation(name, initialMeal) {
var self = this;
self.name = name;
self.meal = ko.observable(initialMeal);
}
// Overall viewmodel for this screen, along with initial state
function ReservationsViewModel() {
var self = this;
// Non-editable catalog data - would come from the server
self.availableMeals = [
{ mealName: "Standard (sandwich)", price: 0 },
{ mealName: "Premium (lobster)", price: 34.95 },
{ mealName: "Ultimate (whole zebra)", price: 290 }
];
// Editable data
self.seats = ko.observableArray([
new SeatReservation("Steve", self.availableMeals[0]),
new SeatReservation("Bert", self.availableMeals[0])
]);
//operations
self.addSeat = function() {
self.seats.push(new SeatReservation("", self.availableMeals[0]));
}
}
ko.applyBindings(new ReservationsViewModel());
有了这个新视图,我得到了
我知道淘汰是新的,但我不明白为什么将显示更改为选择字段应该中断可迭代的
答案 0 :(得分:2)
看看开发者控制台,你会发现错误被抛出:
未捕获的ReferenceError:无法处理绑定“foreach:function (){return seats}“消息:无法处理绑定”值:function (){返回价格}“消息:价格未定义
问题是您尝试访问price
上不存在的SeatReservation
。由于抛出的错误,foreach的渲染会中断。
我认为你不想要price
的下拉菜单,你只想显示他们选择的任何一餐的价格。
答案 1 :(得分:1)