![](/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.