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?
Fiddle: http://jsfiddle.net/viktorb/DKg74/
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 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).
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).
Like the documentation says:
The whole point of observables is that they can be observed, i.e., other code can say that it wants to be notified of changes. That’s what many of KO’s built-in bindings do internally. So, when you wrote data-bind="text: personName", the text binding registered itself to be notified when personName changes (assuming it’s an observable value, which it is now).
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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With