2013-08-23 5 views
2

; 왜 "self.Addticket-function always -1"의 "self.ticketCollection.indexOf (t)"입니까?indexOf가 작동하지 않는 이유는 무엇입니까? 아래 코드에서

page_load 후에, New (newTicket)를 누른 다음 ADT (addTicket)를 push하면됩니다. ("ny", "- 1")의 레코드가 my ticketCollection에 추가됩니다. 다음에이 다른 레코드를 반복하면 정확히 같은 것이 추가됩니다. "self.ticketCollection.indexOf (t)"는 디버거 (FireBug) 두 경우 모두 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 

고맙습니다 사전!

Asle :

답변

4

단지의 BECA 동일한 값을 포함하는 두 개의 Ticket 개체를 사용한다고해서이 두 개체가 동일하다는 것을 의미하지는 않습니다. 따라서 ticketCollection 관찰 할 수있는 배열에는 검사중인 정확한 항목이 포함되어 있지 않으므로 indexOf은 항상 -1을 반환합니다. 이 SO 질문은 좋은 자바 스크립트 객체 평등의 설명이 있습니다 How to determine equality for two JavaScript objects?

대신 배열에 indexOf를 사용하여, 당신이 대신 확인해야합니다을 경우 ticketCollection 경기에서 모든 항목 둘다 ticketName과 새의 cost, 수신 티켓.

내가 무엇을 의미하는지의 예를 추가 할 것입니다 :

for(var i=0, len=self.ticketCollection().length; i < len; i++){ 
if ((t.ticketname() === ticketCollection()[i].ticketname()) && (t.cost() === ticketCollection()[i].cost())) { 
    alert('Found the object in the observable array') 
} 
+0

고맙습니다 패트릭! 너는 내 하루를 보냈다! :) –

관련 문제