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>
= both return correct value.
Can anyone explain to me why this is?
Like the documentation says:
It's about being
observable
or not.See the Reading and writing observables at http://knockoutjs.com/documentation/observables.html for more information.
I've modified your fiddle a bit where you can see the difference with and without the parentheses: http://jsfiddle.net/DKg74/1/
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).
In your 2nd example the binding value is:
selectedMessage() && selectedMessage().message().subject
. When this expression evaluates to thesubject
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).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).