Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

observable array length is always zero

Tags:

knockout.js

Here is the 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 observable array length is always zero. How do I get the correct length?

Edit:
Updated the JS and fixed the errors. 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, no items div will always be visible and if you do self.arry = data, the view won't get updated.

like image 775
firebird Avatar asked Aug 31 '26 21:08

firebird


1 Answers

First thing is: You're never defining the variable self:

var self = this;

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

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

In 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();
like image 132
Niko Avatar answered Sep 04 '26 08:09

Niko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!