我希望能够通过单击列表中的名称从可观察数组中删除项目。但是,我注意到每次将项添加到表或列表时都会触发click事件。在我的情况下,我希望能够单击列表中的项目以将其删除,但绑定remove to click事件将始终导致删除上一项。有没有办法在不使用click事件的情况下执行此操作?下面,我将包含一个jsFiddle,它是淘汰教程的略微修改版本,用于演示此问题。
https://jsfiddle.net/hardrock302/93wdcm65/
以下是代码:
<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());
答案 0 :(得分:2)
匿名函数将为您解决此问题:
<td data-bind="text:name, click: function(data, event) { alert('test')}"></td>
此页面上有关此内容的更多信息:http://knockoutjs.com/documentation/click-binding.html#note-2-accessing-the-event-object-or-passing-more-parameters