Why doesn't ko.observableArray.length return length of underlying array?

Using Knockout, when working with an observableArray, you must grab the underlying array (myArray()) in order to read the length. I don't understand why myArray.length wouldn't return the underlying array's length (instead it returns 0). Is this a bug or is there reason which I've simply missed?

JSFiddle: http://jsfiddle.net/jsm11482/LJVWE/

JS/Model

var data = {
    name: ko.observable("Test"),
    items: ko.observableArray([
        { name: ko.observable("First Thing"), value: ko.observable(1) },
        { name: ko.observable("Second Thing"), value: ko.observable(2) },
        { name: ko.observable("Third Thing"), value: ko.observable(3) }
    ])
};

ko.applyBindings(data, document.getElementsByTagName("div")[0]);

HTML

<div>
    <h1 data-bind="text: name"></h1>
    <ul data-bind="foreach: items">
        <li data-bind="text: value() + ': ' + name()"></li>
    </ul>

    <div>
        <strong>data.items.length == </strong>

        <!-- Expecting 3, get 0. -->
        <span data-bind="text: items.length"></span>
    </div>
    <div>
        <strong>data.items().length == </strong>

        <!-- Expecting 3, get 3. -->
        <span data-bind="text: items().length"></span>
    </div>
</div>

Answers


This is because the plain items observable is in fact a Function, which has its own length property to indicate the number of arguments expected.

From MDN's page on Functions (properties section):

length Specifies the number of arguments expected by the function.

As a developer using the KnockoutJS library I'd also initially expect the length of an observableArray to be the length of the underlying array, but I do appreciate the KO library not overriding this Function property though, as that would probably cause other unwanted side-effects.


Need Your Help

Creating cookies through jquery

jquery cookies

How can I create, delete, edit cookies using jQuery?

Disappearing data MYSQL Database

mysql sql godaddy

I'm using a MySQL database provided by GoDaddy and it was working correctly up until today. Whenever I go to insert data it'll overwrite other rows despite the insert being specified and not update...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.