![](/img/trans.png)
[英]Knockout.js Computed observable not binding to observable array
[英]Observable Binding With Knockout.JS
當我運行此html頁面並單擊select元素中的某些選項時,價格的值會自動更改。 怎么可能? 您能解釋一下選擇elementvalue: meal,
值的功能和作用嗎?
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Working with Lists and Collections</title>
<script type="text/javascript" src="knockout-3.1.0.debug.js"></script>
<script type="text/javascript">
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]));
}
}
</script>
</head>
<body>
<div>
<h2>Your seat reservations</h2>
<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>
</div>
<script type="text/javascript">
ko.applyBindings(new ReservationsViewModel());
</script>
</body>
</html>
這就是設計淘汰賽的方式。 我建議您仔細閱讀Knockout教程,以更好地理解它。
但為回答您的問題,您的select
設置為顯示: $root.availableMeals
,它是所有進餐的數組,定義為:
self.availableMeals = [
{ mealName: "Standard (sandwich)", price: 0 },
{ mealName: "Premium (lobster)", price: 34.95 },
{ mealName: "Ultimate (whole zebra)", price: 290 }
];
數組中的每個項目都有2個屬性: mealName
,這是select
的顯示值, price
是在Surcharge
列中使用的。 顯示值設置為: optionsText: 'mealName'
。
您的UI允許您從此列表中選擇一個選項,然后使用以下選項保存選擇: value: meal
,定義為每個座位預訂的可觀察value: meal
,並定義為默認值:
self.meal = ko.observable(initialMeal);
一旦做出選擇並更新了該值,剔除就可以處理要顯示在“ Surcharge
列上的值。
因為餐食選擇已更新並且是observable
,所以價格會自動更改為與餐食選擇一致,因為綁定已配置為返回座位預訂的所選餐食的price
。
<td data-bind="text: meal().price"></td>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.