Knockout nested objects and parentheses

前端 未结 2 2077

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-pr

相关标签:
2条回答
  • 2021-01-12 22:13

    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).

    0 讨论(0)
  • 2021-01-12 22:19

    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/

    0 讨论(0)
提交回复
热议问题