简体   繁体   English

Knockoutjs不是将数组转换为可观察的数组吗?

[英]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 . 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? 为什么anotherObservableArray无法正常工作?

You should access the underlying array for the length and not the observable array itself. 您应该访问基础数组的长度,而不是可观察数组本身的长度。
anotherObservableArray().length will give you the proper length. anotherObservableArray().length将为您提供适当的长度。

Check this fiddle: http://jsfiddle.net/jfSG8/ 检查此小提琴: http : //jsfiddle.net/jfSG8/

You haven't told us how you are using the var anotherObservableArray , but the following should work: 您尚未告诉我们如何使用var anotherObservableArray ,但是以下方法应该可以工作:

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

With knockout / js: 与淘汰赛/ 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 . 看到这个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. 请注意,我没有使用var来存储可观察数组,而是将其创建为视图模型上的属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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