Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding to nested properties where observables in the chain can be null

I just read about KnockoutJS and when I try to bind to sub-properties on objects that can be null I get binding errors, e.g.:

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

So once you call ko.applyBindings it tries to evaluate the above expression and if selectedAccount is null (which it is by default) it throws an error. I know that I can create a dependentObservable like so:

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

But I was wondering if there's a solution other than putting properties in the ViewModel simply because I get a binding error.

like image 814
Jose Avatar asked Jun 02 '11 13:06

Jose


1 Answers

A couple thoughts:

If you don't want to bother with the dependentObservable, then you can place your statement directly in the text binding like:

<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 the template binding to your advantage when dealing with potentially null values. It would be like this:

<div data-bind="template: { name: 'accountTmpl', data: selectedAccount }"></div>

<script id="accountTmpl" type="text/html">
    ${DocumentList().length}
</script>

Additionally, in the 1.3 release of Knockout there will be some control flow bindings that could be helpful to you. Particularly the "if" or "with" bindings would work for this situation. They are described here: https://groups.google.com/d/topic/knockoutjs/pa0cPkckvE8/discussion

like image 128
RP Niemeyer Avatar answered Sep 21 '22 23:09

RP Niemeyer