The length of the observed array is always zero.

Here is js:

var view = function(){
    self.arry = ko.observable();

    self.arry(ko.mapping.fromJS([{prop:'Test'},{prop:'Test'}]));

    console.log(self.arry().length);       
}
var v = new view();

The length of the observed array is always zero. How to get the correct length?

Edit:
Updated JS and fixed bugs. http://jsfiddle.net/eRHTv/

var view = function(){
  var self = this;
  self.arry = ko.observableArray();

  self.load_items = function(){
    setTimeout(function(){
    self.arry(ko.mapping.fromJS([{prop:'Test'},{prop:'Test'}]));
    }, 100);
  }
  self.no_items_visible = ko.computed(function(){
     return (self.arry().length == 0);
  });

  self.load_items();


  ko.applyBindings(self);
}

var v = new view();

When you run this, the div element will always be visible, and if you do self.arry = data, the view will not be updated.

+3
source share
2 answers

First of all: you never define a variable self:

var self = this;

Secondly: ko.mapping.fromJS () returns an observable array if the input is an array:

self.arry = ko.mapping.fromJS(...);

Total:

var view = function() {
    var self = this;

    self.arry = ko.mapping.fromJS([ {prop:'Test1'}, {prop:'Test1'} ]);

    console.log(self.arry().length);
}

var v = new view();
+4
source

, 0. , ( ko.observableArray(...)) . length.

:

https://github.com/knockout/knockout/issues/4

, : myObservableArray(). length myObservableArray.length.

+2

All Articles