observableArray如何与选项绑定一起使用

时间:2018-06-07 08:58:27

标签: javascript knockout.js

刚从官方网站开始学习Knockoutjs,我正在粘贴this练习第3步的代码。

查看

<table>
    <thead><tr>
        <th>Passenger name</th><th>Meal</th><th>Surcharge</th><th></th>
    </tr></thead>

 <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 data-bind="text: meal().price"></td>
    </tr>    
</tbody>
</table>

<button data-bind="click: addSeat">Reserve another seat</button>

查看模型

// 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[0]),
        new SeatReservation("Bert", self.availableMeals[0])
    ]);

      // Operations
    self.addSeat = function() {
        self.seats.push(new SeatReservation("", self.availableMeals[0]));
    }
}

ko.applyBindings(new ReservationsViewModel());

我想知道ko.observableArray如何使用options绑定,当下拉值更改时价格行如何更新?

是因为座位数组是observableArray所以价格属性在UI中保持同步吗?

我甚至尝试使用chrome进行调试,但是当下拉值改变时,没有任何功能被击中。

任何帮助都会很棒。

1 个答案:

答案 0 :(得分:3)

在您的代码中,价格会因SeatReservation.meal可观察而更新,因为它在您的html模板中绑定到value

因此,当您使用meal().price时,您正在访问膳食中的对象observable,并访问price属性。

与写作相同:

<td data-bind="text:price"></td>

function SeatReservation(name, initialMeal){
this.price = ko.pureComputed(function(){
   return this.meal().price;
});
}