Knockout JS和简单的函数

Knockout JS and simple functions

本文关键字:函数 简单 JS Knockout      更新时间:2023-09-26

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

开门见山,我正在学习淘汰赛,我想在他们的教程中做一些额外的事情。这个图片链接应该非常有用:https://i.stack.imgur.com/cHL7M.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>

视图模型中的第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;
    });
}