Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get an observableArray's length?

Tags:

knockout.js

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 information.

I am able to get the normal observables to work, but it appears that the passing of the array via the constructor for the view model is not creating any part of the clins observable array.

I have a jsFiddle that illustrates my problem. What is strange to me is that the data-bind="text: clins.length() on the HTML span tag does not even return zero, but instead renders nothing.

Is there anyway to enable debugging within a jsFiddle or should I see a warning/error?

like image 250
Karl Anderson Avatar asked Mar 03 '12 04:03

Karl Anderson


People also ask

What is Ko observableArray?

If you want to detect and respond to changes of a collection of things, use an observableArray . This is useful in many scenarios where you're displaying or editing multiple values and need repeated sections of UI to appear and disappear as items are added and removed.

How do you update items in observableArray knockout?

You should look at defining the object structure for each element of your array and then add elements of that type to your observable array. Once this is done, you will be able to do something like item. productQuantity(20) and the UI will update itself immediately. EDIT Added the function provided by the OP :).

How do you make an empty array observable?

To clear an observableArray you can set the value equal to an empty array.

How do I sort knockout observable array?

Description. The KnockoutJS Observable sort() method sorts all items in the array. By default, items are sorted in an ascending order. For sorting an array in a descending order, use reverse() method on sorted array.


1 Answers

Errors from jsfiddle pages do get sent to your browser.

As for your error, try this:

<span data-bind="text: clins().length"> 

This turns the observableArray into an array and uses the array's length property.

See the updated the jsfiddle as well.

like image 51
kendaleiv Avatar answered Sep 20 '22 09:09

kendaleiv