gpt4 book ai didi

javascript - Knockout JS 和简单的功能

转载 作者:行者123 更新时间:2023-12-03 10:25:08 25 4
gpt4 key购买 nike

我希望这个问题还没有被问过:p

开门见山,我正在学习 knockout ,并且想在他们的教程中做一些额外的事情。这个图片链接应该非常有用: /image/cHL7M.png ...在飞机上,有些餐食需要付费,并且选择框会自动更新费用。我想添加一个输入框,将餐费乘以数量,但我不知道如何通过 knockout 来做到这一点。

// 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>

View 模型中的第 5 条注释是我想要放置新函数的部分。

抱歉这个简单的问题,总的来说我对这一切都很陌生。

最佳答案

听起来您想要一个计算属性。这是一个依赖于其他可观察量的属性,并且每当任何依赖项发生变化时都会自动更新。您可以将此计算属性添加到 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;
});
}

关于javascript - Knockout JS 和简单的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29440301/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com