A binding to nested properties where observables in a chain can be null

I just read about KnockoutJS, and when I try to bind objects that may be empty with sub-properties, I get binding errors, for example:

<div data-bind="text: selectedAccount().DocumentList().length"></div> 

So, as soon as you call ko.applyBindings , it tries to evaluate the above expression, and if selectedAccount is null (which is the default), it causes an error. I know that I can create dependentObservable as follows:

 viewModel.docLength = ko.dependentObservable(function () { return selectedAccount() ? selectedAccount().DocumentList().length : null; }) 

But I was wondering if there is a solution other than placing properties in the ViewModel, simply because I get a binding error.

+7
source share
1 answer

A few thoughts:

If you don't want to worry about this dependent, then you can put your statement directly in text binding, for example:

 <div data-bind="text: selectedAccount() ? selectedAccount().DocumentList().length : null"></div> 

or even shorter:

 <div data-bind="text: selectedAccount() && selectedAccount().DocumentList().length"></div> 

Depending on your scenario, you can also use template binding to your advantages when dealing with potentially null values. It will be like this:

 <div data-bind="template: { name: 'accountTmpl', data: selectedAccount }"></div> <script id="accountTmpl" type="text/html"> ${DocumentList().length} </script> 

In addition, in version 1.3 of Knockout, some control flow bindings will appear that may be useful to you. In particular, "if" or "with" bindings will work for this situation. They are described here: https://groups.google.com/d/topic/knockoutjs/pa0cPkckvE8/discussion

+15
source

All Articles