2014-09-21 127 views
0

一直在學習基因敲除和獲得樂趣,但我堅持的東西,我認爲是如此簡單:訪問可觀察數組內的可觀察對象的屬性。 我需要從activeCompMultipliers數組內的activeCompMultiplier對象中獲取「multiplierValue」。訪問observable數組中可觀察對象的屬性 - knockout.js

這裏是我的所有相關代碼:

首先,創建並推入數組對象。這是我想談:

var activeCompMultiplier = function (multiplierValue) { 
    this.multiplierValue = ko.observable(multiplierValue); 
} 

這是包含觀察對象的觀察到的數組:

self.activeCompMultipliers = ko.observableArray(); 

下面是創建一個新的對象,並將其推入行array:

self.activeCompMultipliers.push(new activeCompMultiplier(1)); 

最後,當輸入字段觸發'change'事件時,這就是所謂的。我使用的是警報()來調試問題:

self.inputChanged = function (rowIndex) { 

    alert("Multiplier is: " + self.activeCompMultipliers()[rowIndex].multiplierValue() + "\n At index: " + rowIndex); 
} 

Annnnd這裏我相關的HTML:

<tbody data-bind="foreach: activeParts"> 
       <tr> 
        <td class="ShoppingEntry" data-bind="text: $data"></td> 
        <td class="Textbox" > 
         <input type="number" class="TextBoxInput" 
          data-bind="value: $root.activeCompMultipliers()[$index()], 
            event: { change: inputChanged.bind(self, $index())}, 
            attr: {id: 'Textbox' + $index()}" /></td>  
        <td class="DeleteCell"> 
         <input type="image" src="/Assets/list_remove.png" class="DeleteButtonInput" data-bind="click: deactivatePart"/></td> 
       </tr> 
</tbody> 

我認爲它是一個語法問題,因爲JS是不是我的最強的語言,但我使用圓括號進行三重檢查以取消包裝KO可觀察量,所以也許這是一個範圍問題?

我所有的JS是一個function ViewModel() {...}函數內,即然後通過​​

綁定爲一個長期的潛伏者,我感謝所有幫助。 :)

回答

0

3點:

  1. 你不是遍歷activeCompMultipliers但使用的activeParts$index()來訪問它,這是否意味着這兩個陣列具有相同的尺寸和鏈接?

  2. 如果index()是正確的,值綁定到一個activeCompMultiplier例如,它應該被綁定到其multiplierValue領域:

    <input type="number" class="TextBoxInput" 
        data-bind="value: $root.activeCompMultipliers()[$index()].multiplierValue, 
    
  3. 變化事件勢必inputChanged你改變了它的範圍, self,但是那個時候self是什麼?它的功能已經引用了正確的self。應該是:

    event: { change: function() { inputChanged($index()); } } 
    

    或至少:

    event: { change: inputChanged.bind(null, $index()) } 
    
+0

感謝@manji。您的觀點: 1)是這些陣列是相同的大小和鏈接 2)這是正確的,不知道爲什麼我錯過了...但添加。multiplierValue導致我的HTML變得扭曲 3)分號結束之前是否需要分號?這似乎會導致問題。 – 2014-09-22 05:30:14

+0

我想我會嘗試不使用可觀察的路線,因爲它可能會矯枉過正。我只需抓住爲計算調用inputChanged時傳入的值。 – 2014-09-22 05:54:28

+0

是的,這是一個錯字,帶'bind'的例子不需要分號。 – manji 2014-09-22 09:51:07

相關問題