I'm going through the knockoutjs tutorial. I've slighly modified it to see what happens. So I started with the "working with lists and collections" tutorial. First, I wanted to replace the tag by a div (this didn't work 100% either but that's not the subject of this post). Then, I wanted not only to bind the table cells to model values but also have an event handler for - let's say onClick. Here's the code:
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());
The problem is that the click event isn't handled correctly. With the above code, the click on the input element won't have any effect. If I swap the order of the event and value attributes (data-bind="click: $parent.onClick; value: name;" instead of the code above) the click event works but the data binding doesn't take place (the input remains empty). I see the same effect, even though less surprising if the data-bind tag only contains the click. What am I doing wrong? I want to have both click event handler and data binding for the input element. I'm testing with Firefox on Windows 7.
Many thanks Kai
Bindings in Knockout are separated by a comma, not a semi-colon. Also, leave off the trailing semi-colon.
<input data-bind="value: name, click: $parent.onClick" type="text"/>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.