使用 Knockout,在使用 时observableArray
,您必须获取底层数组 ( myArray()
) 才能读取长度。我不明白为什么myArray.length
不返回底层数组的长度(而是返回 0)。这是一个错误还是我只是错过了的原因?
JSFiddle:http: //jsfiddle.net/jsm11482/LJVWE/
JS/模型
var data = {
name: ko.observable("Test"),
items: ko.observableArray([
{ name: ko.observable("First Thing"), value: ko.observable(1) },
{ name: ko.observable("Second Thing"), value: ko.observable(2) },
{ name: ko.observable("Third Thing"), value: ko.observable(3) }
])
};
ko.applyBindings(data, document.getElementsByTagName("div")[0]);
HTML
<div>
<h1 data-bind="text: name"></h1>
<ul data-bind="foreach: items">
<li data-bind="text: value() + ': ' + name()"></li>
</ul>
<div>
<strong>data.items.length == </strong>
<!-- Expecting 3, get 0. -->
<span data-bind="text: items.length"></span>
</div>
<div>
<strong>data.items().length == </strong>
<!-- Expecting 3, get 3. -->
<span data-bind="text: items().length"></span>
</div>
</div>