淘汰赛JS和简单的功能

问题描述:

我希望这个问题是不是已经问:对淘汰赛JS和简单的功能

直切正题,我正在学习淘汰赛,想做些额外的事情在他们的教程。此图片链接应该非常有用: 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>

在视图模型第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; 
    }); 
} 
+0

谢谢!虽然我注意到ko.pureComputed不起作用,但ko.computed确实是......:d – 2015-04-03 23:04:16