0
我正在通過knockoutjs教程。我已經略微修改它看看會發生什麼。所以我開始使用「使用列表和集合」教程。首先,我想用div替換標籤(這不是100%的工作,但這不是這篇文章的主題)。然後,我不僅要將表格單元格綁定到模型值,而且還要有一個事件處理程序 - 比如onClick。下面的代碼:knockoutjs:值綁定獨佔或點擊事件?
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;」而不是上面的代碼),click事件可以工作,但不會發生數據綁定輸入保持空白)。我看到了同樣的效果,即使數據綁定標籤只包含點擊,這並不令人驚訝。 我在做什麼錯?我想同時爲輸入元素單擊事件處理程序和數據綁定。 我使用Firefox在Windows 7測試
非常感謝 凱