我希望这个问题还没有被问到:p
直截了当地说,我正在学习淘汰赛,并希望在他们的教程中做一些额外的事情。这个图片链接应该非常有用: http://i.imgur.com/01mn8C4.png ...... 在飞机上,有餐费用,选择框会自动更新费用。我想添加一个输入框,它将膳食成本乘以数量,但我不知道如何通过淘汰赛来实现这一目标。
// 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[2]),
new SeatReservation("Bert", self.availableMeals[1])
]);
//Something extra I want to know how to do with knockout, i just want the "total" to be the "quantity" times the price of the "meal"
var mealPrice = //what should go here?!?!?!
this.quantity = ko.observable(1) //is this correct?
var quantity = this.quantity
var finalPrice = function() {
quantity * mealPrice;
}
self.addSeat = function() {
self.seats.push(new SeatReservation("", self.availableMeals[0]));
}
}
ko.applyBindings(new ReservationsViewModel());
//end

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<h2>Your seat reservations</h2>
<table>
<thead><tr>
<th>Passenger name</th><th>Meal</th><th>Quantity</th><th>Total</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><input data-bind="value: quantity" /></td>
<td data-bind="text: finalPrice"></td>
</tr>
</tbody>
</table>
<button data-bind="click: addSeat">Reserve another seat</button>
&#13;
视图模型中的第5条评论是我想要放置新函数的部分。
很抱歉这个简单的问题,我对这一切都很新。
答案 0 :(得分:1)
听起来你想要一个计算属性。这是一个依赖于其他observable的属性,并且只要任何依赖项发生更改,它就会自动更新。您可以将此计算属性添加到SeatReservation
以获取每个座位餐的总价格。
function SeatReservation(name, initialMeal) {
var self = this;
self.name = ko.observable(name);
self.meal = ko.observable(initialMeal);
self.quantity = ko.observable(1);
this.finalPrice = ko.computed(function() {
var quantity = self.quantity(),
meal = self.meal() || {},
price = meal.price || 0;
return price * quantity;
});
}