2012-11-08 46 views
3

淘汰賽發出這段代碼與optionsValue和觀察到的陣列

function Order(name, initialMeal) { 
    var self = this; 
    self.name = name; 
    self.meal = ko.observable(initialMeal); 
} 

function OrdersViewModel() { 
    var self = this; 
    self.availableMeals = [ 
     { menuItem:"Chicken", calories:1000, price:12 }, 
     { menuItem:"Eggs", calories:900, price:10 }, 
     { menuItem:"Fries",calories:700, price:15 } 
    ]; 

    self.orders = ko.observableArray([ 
     new Order("Mike", self.availableMeals[0]), 
     new Order("John", self.availableMeals[0]), 
     new Order("Larry", self.availableMeals[0]) 
    ]); 
    self.addOrder = function(){ 
     self.orders.push(new Order("", self.availableMeals[0])); 
    } 
} 
ko.applyBindings(new OrdersViewModel()); 

我有以下幾點看法

<tbody data-bind="foreach: orders"> 
     <tr> 
      <td><input data-bind="value: name" /></td> 
      <td><select data-bind="options: $root.availableMeals, value: meal, optionsValue: 'price', optionsText: 'menuItem'"></select></td> 
      <td data-bind="text: meal().price"></td> 
     </tr> 
    </tbody> 

你也許可以找到它在淘汰賽的例子。問題是最後一個綁定餐()。當optionsValue存在於其上時,價格似乎不起作用。如果我刪除optionsValue它工作得很好。我錯過了什麼嗎? 謝謝。

回答

1

是的,你錯過了一些東西。

沒有指定optionsValue,您正在綁定一個meal對象(從availableMeals數組)到訂單的meal屬性。該price結合的外觀上,你綁定的mealprice屬性,它發現它,因爲它發現這個對象:

{ menuItem:"Eggs", calories:900, price:10 } 

這工作。

當您將optionsValue指定爲price時,您將一個數字綁定到訂單的meal屬性。 price綁定查找該號碼上的price屬性,該屬性不存在。

這是所有正確的行爲。當您實際需要您指定的財產時,您應該只使用optionsValue。這通常只在您想綁定到您綁定到下拉列表的某個列表的ID時纔有必要,就像您可能從數據庫中獲得的列表一樣。由於您正在綁定的對象上使用其他屬性(價格),因此最好通過讓它綁定整個對象以便稍後使用整個對象來提供服務。