Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

knockout if length issue

Tags:

knockout.js

I'm a little bit new with knockout and I can't get the if data-bind to work...

html:

<div data-bind="if: items.length">
    <h1>List</h1>

    <ul data-bind="foreach: items">
        <li data-bind="text: $data">
            &nbsp;
        </li>
    </ul>
</div>

javascript:

model =
    items: ko.observableArray(["A", "B", "C"])

ko.applyBindings(model)

sandbox: http://jsfiddle.net/gibatronic/EXwrR/

why the if: items.length doesn't work? knockout documentation says that it accepts that kind of test. I saw that length is always zero by changing the data-bind to if: console.log(items.length). will I have to make an observable and manually manage that?

like image 258
gibatronic Avatar asked Apr 23 '26 17:04

gibatronic


1 Answers

Just change code to use items().length instead of items.length

<div data-bind="if: items().length">
    <h1>List</h1>
..

length is native JavaScript array function that operate on underlying array.


Take a look on Knockout.js documentation. There you can find a lot of useful information.
From documentation:

You can get the underlying JavaScript array by invoking the observableArray as a function with no parameters, just like any other observable.

like image 155
Anatolii Gabuza Avatar answered Apr 26 '26 17:04

Anatolii Gabuza