剔除viewmodel属性未定义 [英] knockout viewmodel property undefined
问题描述
我有一个简单的foreach:
I have a simple foreach:
<div id="customersArea" data-bind="foreach: people">
<div class="section" data-bind="attr: { 'personid': PersonId }" >
<div class="sectionActions">
<div><a class="action" href="#" data-bind='click: $parent.removePerson'>Remove</a></div>
</div>
<div class="sectionText">
<span data-bind="if:LastName, text:LastName"></span>
<span data-bind="if:FirstName, text:FirstName"></span>
<span data-bind="if:MailingAddress">
<span data-bind="with:MailingAddress">
<span data-bind="text:StreetPartOne"> </span>
<span data-bind="text:StreetPartTwo"> </span>
<span data-bind="text:City"></span>
<span data-bind="text:PostalCode"></span>
</span>
</span>
<span data-bind="if:EmailAddress, text:EmailAddress"></span>
<span data-bind="if:MainPhoneNumber, text:MainPhoneNumber"></span>
<span data-bind="if:MobilePhoneNumber, text:MobilePhoneNumber"></span>
</div>
<div class="sectionOptions">
</div>
</div>
</div>
我正在尝试使其能够与模型{PersonId:33}绑定,而其余的如果丢失就不会呈现.当我尝试这种方式和其他方式时
I am trying to make it such that i can bind against a model {PersonId:33} and the rest will just not render if missing. when i try it this and other ways i get
Uncaught Error: Unable to parse bindings.
Message: ReferenceError: MailingAddress is not defined;
Bindings value: if:MailingAddress
我创建了一个简单的jsfiddle进行测试:
I created a simple jsfiddle to test:
推荐答案
因此,您有一些选择:
-
当您尝试绑定未定义的属性时,
-
KO会出现问题,除非它们不在对象之外.因此,您可以在各种绑定之前加上
$data.
作为前缀,并且KO将能够解析您的绑定.示例: http://jsfiddle.net/rniemeyer/dLCL8/如果您知道总是会有几个属性在一起,则可以在这些选项周围使用with
或if
语句.
KO will have an issue when you try to bind against undefined properties, unless they are off of an object. So, you can prefix your various bindings with
$data.
and KO will be able to parse your bindings. Sample: http://jsfiddle.net/rniemeyer/dLCL8/ If you know that several properties will always be together, then you could use awith
orif
statement around those options.
处理未定义"属性的另一种方法是创建一个绑定,当缺少这些属性时,将填充这些属性.查看此答案.这将是相似的,但可能带有文本"绑定.样本: http://jsfiddle.net/rniemeyer/dLCL8/4/
A different take on handling "undefined" properties is to create a binding that populates these properties when they are missing. Look at this answer. It would be similar, but potentially with the 'text' binding. Sample: http://jsfiddle.net/rniemeyer/dLCL8/4/
这篇关于剔除viewmodel属性未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!