2017-05-31 22 views
0

我試圖結合使用$parent外部foreach數據的每一行的數據,但它會引發錯誤Unable to parse bindings對於低於代碼:(KnockoutJS)在foreach外部參照數據

HTML:

<table> 
    <thead> 
     <tr> 
      <th class="col_name">Name</th> 
      <th class="col_dob">DOB</th> 
      <th class="col_address">Address</th> 
     </tr> 
    </thead> 
    <tbody data-bind="foreach: rows"> 
     <tr data-bind="attr: { id: resource.id}, style: { background-color: $parent.isSel}, event:{click: $parent.selectRow} "> 
      <td class="col_name" data-bind="text: resource.name"></td> 
      <td class="col_dob" data-bind="text: resource.birthDate"></td> 
      <td class="col_address" data-bind="text: resource.address"></td> 
     </tr> 
    </tbody> 
</table> 

當我將刪除style: { background-color: $parent.isSel}, event:{click: $parent.selectRow}所有工作正常。上述

KnockoutJS一部分看上去都迄今爲止這樣的:

this.isSel = ko.observable("#fff"); 

this.selectRow = function() { 
    var self = this; 
    self.isSel("#ccc"); 
    console.log("Row selected"); 
} 

對任何提示?

回答

3

您的$parent使用情況沒有任何問題,但使用屬性名稱:background-color

虛線在JS對象屬性名稱中無效。因此,你需要用引號引起來包裝background-color

<tr data-bind="attr: { id: resource.id}, 
       style: { 'background-color': $parent.isSel}, 
       event:{click: $parent.selectRow} "> 

也看到documentation

+0

幾乎那裏 - 沒有線索爲什麼我得到TypeError:self.isSel不是一個單擊事件的函數錯誤。我是否應該將'$ parent'作爲該功能的目標? – JackTheKnife

+1

當您使用'$ parent'時,'this'不會指向您的實際父級,因此您需要'綁定它:'event:{click:$ parent.selectRow.bind($ parent)}'或移動在你的主視圖模型函數對象的'selectRow'之外的'var self = this;' – nemesv