淘汰赛无法处理绑定 [英] Knockout unable to process binding
问题描述
当文本未定义时如何绑定文本?例如,名称不可用:
How do I bind a text when it is undefined? For example name is not available:
<table id="recordTbl" data-bind="visible: records().length > 0" class="table">
<thead>
<tr>
<th class="col-md-4">ID</th>
<th class="col-md-4">Name</th>
</tr>
</thead>
<tbody data-bind="foreach: records">
<tr>
<td data-bind="text: id"></td>
<td data-bind="text: name"></td>
</tr>
</tbody>
</table>
我收到此错误:
Uncaught ReferenceError: Unable to process binding "text: function (){return name }"
Message: name is not defined
推荐答案
您可以使用$data
绑定上下文属性,该属性始终代表当前视图模型以通过它访问name
:
You can you the $data
binding context property which always represents the current view model to access the name
through it:
<tbody data-bind="foreach: records">
<tr>
<td data-bind="text: id"></td>
<td data-bind="text: $data.name"></td>
</tr>
</tbody>
使用这种方法,如果records
中的一项不具有name
属性,则KO不会引发异常.
With this approach KO won't throw an exception if one of the items in the records
does not have a name
property.
没有$data
,则未定义名为name
的标识符.但是$data.name
始终是有效的表达式,如果当前视图模型没有名为name
的属性,它只会返回undefined
.
Without the $data
the identifier named name
is undefined. However $data.name
is always a valid expression it just returns undefined
if the current view model does not have a property named name
.
这篇关于淘汰赛无法处理绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!