2012-08-23 77 views
1

我是KnockoutJS的新手,我遇到了一些問題。選定的項目無法使用KnockoutJS

我不明白爲什麼selectedOf點擊後沒有更新。

有人可以發現我做錯了什麼嗎?

<div> 
    <ul data-bind="foreach: Ofs"> 
     <li data-bind="text: Number, click: $root.selectOf" style="cursor:pointer"/> 
    </ul> 
    <strong>Item clicked: </strong><span data-bind="text: selectedOf.Number" /> 
</div> 

<script type"text/javascript"> 
    var OfsModel = function (initialData) { 
     //console.log(initialData); 
     var self = this; 
     self.CurrentState = ko.observable(initialData.CurrentState); 
     self.Ofs = ko.observableArray(initialData.Ofs); 
     self.selectedOf = ko.observable(); 

     self.selectOf = function (of) { 
      //console.log(of); 
      self.selectedOf(of); 
      //console.log(self.selectedOf()); 
     } 
    } 

    var initialData = '{"Ofs":[{"Client":"A","Number":"1","Qty":10,"QtyRejected":5,"StopReason":"","ModifiedOn":"\/Date(1345732172456)\/","IsHighlighter":false,"SequencesAvailable":[{"Id":1,"Name":"Seq1"},{"Id":2,"Name":"Seq2"},{"Id":3,"Name":"Seq3"}],"SelectedSequence":null},{"Client":"B","Number":"2","Qty":20,"QtyRejected":0,"StopReason":"too much work","ModifiedOn":"\/Date(1345732172457)\/","IsHighlighter":false,"SequencesAvailable":[{"Id":1,"Name":"Seq1"},{"Id":2,"Name":"Seq2"}],"SelectedSequence":null},{"Client":"C","Number":"3","Qty":30,"QtyRejected":0,"StopReason":"","ModifiedOn":"\/Date(1345732172457)\/","IsHighlighter":false,"SequencesAvailable":[{"Id":1,"Name":"Seq1"}],"SelectedSequence":null}],"CurrentState":""}'; 

    var vw = $.parseJSON(initialData); 
    ko.applyBindings(new OfsModel(vw)); 
</script> 

編輯: 我把http://jsfiddle.net/muek/KBeZ3/2/

回答

1

代碼當您訪問Number物業斷selectedOf,那麼你需要調用它沒有一個函數來獲取對觀察到的第一個值參數如selectedOf().Number

但是,如果您在填充selectedOf之前執行此操作,則會嘗試訪問Number以導致未定義值出錯。

一個很好的解決方法是使用類似with綁定的東西來爲元素的子元素設置範圍。它也可以防止空。這看起來像:

<div data-bind="with: selectedOf"> 
    <strong>Item clicked: </strong><span data-bind="text: Number" /> 
</div> 

這裏有一個例子:http://jsfiddle.net/rniemeyer/ecDgD/

或者你可以創建一個計算觀察到的Number值防止空或綁定像data-bind="text: selectedOf() ? selectedOf().Number : 'none'"

+0

謝謝你,它完美地工作 – muek