当我运行此 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 的设计原理。我建议浏览Knockout Tutorials以便更好地理解它。
但是为了回答您的问题,您的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
,它用于附加费
列。显示值设置为:optionsText: 'mealName'
。
您的 UI 允许您从此列表中选择一个选项,并使用以下选项保存选择:值:餐
,它被定义为每个座位预订的可观察值,定义为默认值:
self.meal = ko.observable(initialMeal);
一旦做出选择并且该值已更新, knockout 就会开始处理要在附加费
列上显示的值。
由于餐食选择已更新且可观察
,因此价格会自动更改以与餐食选择一致,因为您的绑定(bind)配置为返回价格
预订座位时选择的餐食。
<td data-bind="text: meal().price"></td>
JSFiddle For Reference
关于javascript - 使用 Knockout.JS 进行可观察绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24491731/