I am attempting to create an array of contract line items (CLINs) that will be displayed as individual div elements below a header of general contract informati
Execute the observableArray as a function to get the underlying array, then get its length:
myObsArray's length is:
Let me provide an answer that provides some details in addition to @kendaleiv's solution, and that also answers a highly related question I feel many people have:
Why does
myObsArray.lengthalways return 0 (zero)?
A typical repro of such a scenario would be this:
ko.applyBindings({ myObsArray: ko.observableArray(["one", "two", "three"]) });
myObsArray.length =
The snippet says "length = 0", instead of "length = 3".
The key thing to note here: ko.observableArray is a function... that returns a function.
That's right: if you assign the result of it to a variable or member, such as myObsArray in the example, that variable will be a reference to a function. So if you're asking for
myObsArray.length
then you're actually asking for the Function.length property: the number of arguments that function takes. For a function returned from ko.observableArray this will be 0 (zero).
The fix given in other answers is fine, let me reiterate here with this answer's example. To get the length of "the array being observed", you need to invoke said function to get the array, and then get its length:
ko.applyBindings({ myObsArray: ko.observableArray(["one", "two", "three"]) });
myObsArray.length =
Finally, as a footnote, OP's code is something equivalent to:
myObsArray.length()
This will find aforementioned Function.length property and try to execute it as a function (which it isn't), and will not return 0 but instead crash. Beware to not invoke length as a function, but the observable. Always invoke length as a member variable.
Very early on KO's developers considered this issue; as early as Github issue no 4. That issue explains the things I've tried to cover above too, and also shows that in the end there wasn't much that could be done to change it.