我正在学习knockoutjs 教程。我稍微修改了一下,看看会发生什么。所以我从“使用列表和集合”教程开始。首先,我想用 div 替换标签(这也不是 100% 有效,但这不是本文的主题)。然后,我不仅想要将表格单元格绑定(bind)到模型值,还想要一个事件处理程序 - 比如说 onClick。代码如下:
HTML:
<h2>Your seat reservations</h2>
<div data-bind="foreach: seats">
<div style="clear: left; display: table; width: 100%;" >
<input data-bind="value: name; click: $parent.onClick;" type="text"/>
</div>
<div style="width: 300px; float: left; display: table; width: 100%">
<select data-bind="options: $root.availableMeals, value: meal, optionsText: 'mealName'; select: $root.onClick"></select>
</div>
</div>
<button data-bind="click: addSeat">Reserve another seat</button>
JS:
// 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]),
new SeatReservation("Kai", self.availableMeals[0])
]);
// Operations
self.addSeat = function() {
self.seats.push (new SeatReservation ("<Please fill>", self.availableMeals[0]));
}
self.onClick = function () { alert ('Lets make love'); }
}
ko.applyBindings(new ReservationsViewModel());
问题是点击事件处理不正确。使用上面的代码,点击输入元素不会有任何效果。如果我交换事件和值属性的顺序(data-bind="click: $parent.onClick; value: name;"而不是上面的代码),则单击事件有效,但数据绑定(bind)不会发生(输入保持为空)。我看到了相同的效果,尽管如果数据绑定(bind)标记仅包含点击就不那么令人惊讶了。 我究竟做错了什么?我想要为输入元素提供点击事件处理程序和数据绑定(bind)。 我正在 Windows 7 上使用 Firefox 进行测试。
非常感谢 凯
最佳答案
Knockout 中的绑定(bind)由逗号分隔,而不是分号。另外,请省略尾随的分号。
<input data-bind="value: name, click: $parent.onClick" type="text"/>
关于javascript - knockout : value binding exclusive or click event?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20529626/