2015-04-03 93 views
0

我希望這個問題是不是已經問:對淘汰賽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的評論是,我希望把新的功能的一部分。

對不起這個簡單的問題,我對所有這一切都非常陌生。

回答

1

這聽起來像你想要一個計算屬性。這是一個依賴於其他觀察對象的屬性,只要有任何依賴關係發生變化,它就會自動更新。您可以將此計算的屬性添加到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