在下面的代码中;为什么“self.Addticket-function”中的“self.ticketCollection.indexOf(t)”总是-1?
在 page_load 之后,我推送 New (newTicket),然后是 ADD (addTicket)。这可以正常工作,并且 ("ny","-1") 的记录被添加到我的 ticketCollection 中。然后,当我重复此操作时,添加了另一条完全相同的记录。调试器(FireBug)告诉我“self.ticketCollection.indexOf(t)”在这两种情况下都是-1。为什么?
function Ticket(ticketname, cost) {
var self = this;
//alert("ikke implementer fullt ut ennå!");
self.ticketname = ko.observable(ticketname);
self.cost= ko.observable(cost);
} // end Ticket
//==============================================================
function ViewModel() {
var self = this;
//------ initiate ----------------------------------------------
// the product we want to view/edit
self.selectedTicket = ko.observable();
self.ticketCollection = ko.observableArray(
[
new Ticket("Bus", "$2"),
new Ticket("Ferry", "$3"),
new Ticket("Bicycle", "$1")
]);
// selected item from ticket list-view
self.listViewSelectedItem = ko.observable();
// push any changes in the list view to our main selectedTicket
self.listViewSelectedItem.subscribe(function (ticket) {
if (ticket) {
self.selectedTicket(ticket);
}
}); // self.listViewSelectedItem.subscribe //
//---- NEW button pressed --------------------------------------
self.newTicket = function () {
// create a new instance of a Ticket
var t = new Ticket("ny", "-1");
// set the selected Ticket to out new instance
self.selectedTicket(t);
}.bind(this);
//---- ADD to collection -----------------------------------------
self.addTicket = function () {
//alert("ADD is pushed!");
// get a reference to out currently selected product
var t = self.selectedTicket();
// ignore if null
if (!t) { return; }
// check to see that the ticket doesn\t already exist
if (self.ticketCollection.indexOf(t) > -1) {
return;
}
// add the product to the collection
self.ticketCollection.push(t);
// clear out the selected product
self.selectedTicket(t);
//self.listViewSelectedItem(t)
};
} // end ViewModel
提前谢谢!
阿斯莱 :)