【发布时间】:2013-02-02 02:19:33
【问题描述】:
我正在查看 Knockoutjs.com 上的 @ 2'nd 教程“使用列表和集合”:http://learn.knockoutjs.com/#/?tutorial=collections
这是 HTML:
您的座位预订 ()
<table>
<thead><tr>
<th>Passenger name</th><th>Meal</th><th>Surcharge</th><th></th>
</tr></thead>
<!-- Todo: Generate table body -->
<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: formatterPrice"></td>
<!--<td> <a href="#" data-bind="click: $root.removeSeat">Remove</a></td>-->
<td> <button data-bind="click: $root.removeSeat">Remove</button></td>
</tr>
</tbody>
</table>
<button data-bind="click: addSeat, enable: seats().length < 5">Reserve another seat</button>
<h3 data-bind="visible: totalSurcharge() > 0">
Total surcharge: $<span data-bind="text: totalSurcharge().toFixed(2)"></span>
</h3>
<span data-bind="text: seats()[0].name()" ></span> <br/>
<span data-bind="text: seats()[0].meal().mealName" />
这里是 ViewModel:
// Class to represent a row in the seat reservations grid
function SeatReservation(name, initialMeal) {
var self = this;
self.name = ko.observable(name);
self.meal = ko.observable(initialMeal);
self.formatterPrice = ko.computed(function() {
var price = self.meal().price;
return price ? "$" + price.toFixed(2) : "None";
});
}
// 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.958989 },
{ mealName: "Ultimate (whole zebra)", price: 290.00000 }
];
// Editable data
self.seats = ko.observableArray([
new SeatReservation("Steve", self.availableMeals[0]),
new SeatReservation("Bert", self.availableMeals[1])
]);
self.addSeat = function() {
self.seats.push(new SeatReservation("Steve", self.availableMeals[2]))
};
self.removeSeat = function(seat) {
self.seats.remove(seat);
}
self.totalSurcharge = ko.computed(function() {
var total = 0;
for(var i = 0; i < self.seats().length; i++) {
total += self.seats()[i].meal().price;
}
// alert(total);
return total;
});
}
ko.applyBindings(new ReservationsViewModel());
当我尝试更改文本框中的“名称”时,我的 observableArray(座位)似乎没有改变。如果我尝试更改第一行的文本框,我的 span @bottom 仍然显示“Steve”。
我已将 name() 设置为与用餐相同的可观察性,如果我更改用餐(下拉菜单),我的 observableArray(座位)似乎工作。
请帮忙!
【问题讨论】:
-
设置名称的“值”属性设置为 name() 而不是 name 是否重要?
-
afaik,当我们使用 observable 时,get is by () 表示 name() 而不是 name only。
-
是的,但是对于值绑定,你不只是想要一个“get”,如果你想要双向绑定,你希望绑定表达式计算为实际的 observable,而不是它的值. (即使你只是想要一个 get,如果绑定表达式的计算结果为 observable 也没问题,KO 会根据需要展开它)
-
@Michael Welburn,你答对了,我只需要使用 name 而不是 name() @ Antishok,感谢您的解释