剔除嵌套对象和括号 [英] Knockout nested objects and parentheses
问题描述
我没得到的东西. 根据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屋!