qtime67
qtime67

Reputation: 317

KnockoutJS observable array - how to get length

I have a KnockoutJS model which has observable arrays, that I need to be able to both load from JSON, and also add to by simply pushing data objects to the array. I am finding that when I load data using mapping, I can no longer get the length/count of items in an array, it is always equal to zero. I think this is due to the mapping?

Here is the ghist:

var SalesPerson = function (data) {
    var self = this;
    if (data != null) {
        ko.mapping.fromJS(data, {Regions: regionMapping, Customers: customerMapping},     self); 
    } else {
        self.ID = ko.observable();
        self.FullName = ko.observable().extend({
            required: {
                message: '* Persons name needed'
            }
        });
        //self.Regions = ko.observableArray(); 
         self.Regions = ko.mapping.fromJS([]);
         self.Customers = ko.mapping.fromJS([]);
         //self.Customers = ko.observableArray(); // array of "Customers", who each     have many orders
    }

Note I originally was putting in the array using eg self.Regions = ko.observableArray();, then changed to this self.Regions = ko.mapping.fromJS([]); after seeing a related post

Here is a fiddle of the entire: fiddle example

To test the fiddle, click "Load from in-line model" .. the "count" of regions and customers should update but it does not, it stays at zero.

Upvotes: 1

Views: 3793

Answers (1)

GSerjo
GSerjo

Reputation: 4778

An observable is a function, so you have to call it before accessing any property.

So it should be text:Regions().length not text:Regions.length

Here's updated version

Upvotes: 4

Related Questions