user2281858
user2281858

Reputation: 1997

TypeError: someProperty(...) is null - knockout

I am trying to this piece of code where someProperty().length is returning me the length of the property and is inside a foreach loop

<p data-bind="html: (someProperty().length == null ? 0 : someProperty().length)"></p>

but getting the following error in firefox.

TypeError: someProperty(...) is null

Upvotes: 0

Views: 109

Answers (1)

Joel R Michaliszen
Joel R Michaliszen

Reputation: 4222

In JS some values are considered false in conditions expressions like: "", null, undefined and 0. So you dont need to verify if the html string has lenght, an empty string aways has lenght == 0 and "" is equal false, so you just need to do this : !someProp() ? 0 : someProp().length, with this condition the 0 will be applied when somePropperty() returns any false synonymous, and the length of a string never will be null, if it is empty the length will be 0, see in the snippet how optimize you ternary in the data-bind attr:

function viewModel()
{
  this.someProp = ko.observable("<strong>TEST</strong>");
};

ko.applyBindings(new viewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<p data-bind="html: someProp && !someProp() ? 0 : someProp().length "></p>

Upvotes: 2

Related Questions