正如@DCoder 所说,您每次都将相同的对象添加到数组中。并且删除函数会删除数组中所有重复的对象。
你的代码是你尝试做的一半。
首先,这是一个更新的 jsfiddle 做你想做的事(我认为)。
http://jsfiddle.net/pQN32/5/
顺便说一句,如果你的availableMeals 永远不会改变,你就不需要ko.observableArray
HTML
<h2>Your seat reservations (<span data-bind="text: seats().length"></span>)</h2>
<table>
<thead><tr>
<th>Passenger name</th><th>Meal</th><th>Price</th><th>Surcharge</th><th></th>
</tr></thead>
<tbody data-bind="foreach: seats">
<tr>
<td data-bind="text: name"></td>
<td><select data-bind="options: $root.availableMeals, optionsText: 'mealName', value: meal"></select></td>
<td data-bind="text: formattedPrice"></td>
<td></td>
<td><a href="#" data-bind="click: $root.removeSeat">Remove</a></td>
</tr>
</tbody>
</table>
<input data-bind="value: customerName, valueUpdate: 'afterkeydown'" placeHolder="Customer Name"/>
<select data-bind="options: availableMeals, optionsText: 'mealName', value: selectedMeal, optionsCaption: 'Select a meal...'"></select>
<button data-bind="click: addSeat, enable: seats().length < 5 && selectedMeal() && customerName() && customerName().length > 0">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);
self.formattedPrice = ko.computed(function() {
var price = self.meal().price;
return price ? "$" + price.toFixed(2) : "None";
});
}
// 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 }
];
self.selectedMeal = ko.observable();
self.customerName = ko.observable();
// Editable data
self.seats = ko.observableArray([]);
// Operations
self.addSeat = function() {
self.seats.push(new SeatReservation(self.customerName(), self.selectedMeal()));
// reset inputs
self.customerName(undefined);
self.selectedMeal(undefined);
}
self.removeSeat = function(seat) { self.seats.remove(seat) }
}
ko.applyBindings(new ReservationsViewModel());