剔除嵌套对象和括号 [英] Knockout nested objects and parentheses

查看:53
本文介绍了剔除嵌套对象和括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我没得到的东西. 根据KO文档(以及有关SO的许多文章),在查询和编写可观察值时应使用括号.但是在绑定子属性时,在我看来,是否使用括号都没有关系.

Few things I don't get. According to KO documentation (and many posts here on SO), parentheses should be used when querying and writing observables. But when binding sub-properties it seems to me that it doesn't matter if you use parentheses or not.

<span data-bind="text: selectedMessage() && selectedMessage().message().subject()"></span>
<span data-bind="text: selectedMessage() && selectedMessage().message().subject"></span>

=都返回正确的值.

有人可以向我解释为什么吗?

Can anyone explain to me why this is?

提琴: http://jsfiddle.net/viktorb/DKg74/

推荐答案

如果绑定值是可观察的,则KO为您解包"它,因此您不必自己用括号将其解包(或调用)到ko.utils.unwrapObservable).

If the binding value is an observable, KO "unwraps" it for you, so you don't have to unwrap it yourself with the parentheses (or a call to ko.utils.unwrapObservable).

在第二个示例中,绑定值是:selectedMessage() && selectedMessage().message().subject.当此表达式的值为subject属性时,KO会看到评估的值是可观察的,因此它将为您解包. (在内部,这可能只是对ko.utils.unwrapObservable的调用).

In your 2nd example the binding value is: selectedMessage() && selectedMessage().message().subject. When this expression evaluates to the subject property, KO sees that the evaluated value is an observable, and so it unwraps it for you. (Internally this is probably just a call to ko.utils.unwrapObservable).

但是,由于表达式并非计算出的message属性(我认为也是可观察的),因此访问该属性的括号是必需的(例如,selectedMessage().message.subject不起作用).

But, since the expression doesn't evaluate to the message property, which I'm assuming is also an observable, the parentheses for accessing that property are necessary (e.g. selectedMessage().message.subject wouldn't work).

这篇关于剔除嵌套对象和括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆