2017-05-31 62 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