简体   繁体   中英

Knockoutjs is not converting array into observable array?

I am using this knockoutjs tutorial to convert array into observable array. http://knockoutjs.com/documentation/observableArrays.html . But the given following line is giving me an array of zero length.

var anotherObservableArray = ko.observableArray([
    { name: "Bungle", type: "Bear" },
    { name: "George", type: "Hippo" },
    { name: "Zippy", type: "Unknown" }
]);

Why anotherObservableArray is not working?

You should access the underlying array for the length and not the observable array itself.
anotherObservableArray().length will give you the proper length.

Check this fiddle: http://jsfiddle.net/jfSG8/

You haven't told us how you are using the var anotherObservableArray , but the following should work:

<ul data-bind="foreach: anotherObservableArray">
    <li data-bind="text: name"></li>
</ul>

With knockout / js:

var viewModel = function() {
  this.anotherObservableArray = ko.observableArray([
    { name: "Bungle", type: "Bear" },
    { name: "George", type: "Hippo" },
    { name: "Zippy", type: "Unknown" }
  ]);
};

ko.applyBindings(new viewModel());

See this jsfdiddle .

Note that I'm not using a var to store the observable array, but instead creating it as a property on the view model.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM