7

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.

1 Answer 1

14

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

2
  • Wouldn't it be better to put the null check responsibility on the framework? I guess it would require to split up the properties in the expression and subscribe to each tier.
    – Jose
    Jun 2, 2011 at 17:56
  • 1
    The if/with bindings coming in 1.3 with do that null checking and quit trying to bind things, so there will be support in the framework soon. I was mainly trying to show ways that you can do it in the current version of Knockout. Jun 2, 2011 at 18:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.