Skip to content Skip to sidebar Skip to footer

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 ret

Solution 1:

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.

Solution 2:

This is because ko.observableArray is not really an array. It is a function that returns the underlying array.

In your example, since items is a function, you get a .length = 0.

Please check this fiddle where I have added spans with some additional properties

http://jsfiddle.net/LJVWE/3/

Post a Comment for "Why Doesn't Ko.observablearray.length Return Length Of Underlying Array?"