Reputation: 411
I would like to be able to remove an item from an observable array by clicking on the name in a list. However, I have noticed that the click event fires every time an item is added to the table or list. In my case, I want to be able to click on an item in a list to remove it, but binding the remove to click event will always cause the previous item to be removed. Is there a way to do this without using the click event? Below, I will include a jsFiddle that is a slightly modified version of the knockout tutorial that demonstrates the issue.
https://jsfiddle.net/hardrock302/93wdcm65/
Here's the code:
<h2>Your seat reservations</h2>
<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 data-bind="text:name, click:alert('test')"></td>
</tr>
</tbody>
</table>
// 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])
]);
}
ko.applyBindings(new ReservationsViewModel());
Upvotes: 1
Views: 1434
Reputation: 2617
An anonymous function will solve this problem for you:
<td data-bind="text:name, click: function(data, event) { alert('test')}"></td>
More information about this on this page: http://knockoutjs.com/documentation/click-binding.html#note-2-accessing-the-event-object-or-passing-more-parameters
Upvotes: 2