Knockout unable to process binding

匿名 (未验证) 提交于 2019-12-03 02:34:02

问题:

How do I bind a text when it is undefined? For example name is not available:

<table id="recordTbl" data-bind="visible: records().length &gt; 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> 

I get this error:

Uncaught ReferenceError: Unable to process binding "text: function (){return name }" Message: name is not defined  

回答1:

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> 

With this approach KO won't throw an exception if one of the items in the records does not have a name property.

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!