javascript - Why doesn't ko.observableArray.length return length of underlying array? -
using knockout, when working observablearray
, must grab underlying array (myarray()
) in order read length. don't understand why myarray.length
wouldn't return underlying array's length (instead returns 0). bug or there reason i've missed?
jsfiddle: http://jsfiddle.net/jsm11482/ljvwe/
js/model
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, 0. --> <span data-bind="text: items.length"></span> </div> <div> <strong>data.items().length == </strong> <!-- expecting 3, 3. --> <span data-bind="text: items().length"></span> </div> </div>
this because plain items
observable in fact function, has own length
property indicate number of arguments expected.
from mdn's page on functions (properties section):
length
specifies number of arguments expected function.
as developer using knockoutjs library i'd expect length of observablearray length of underlying array, appreciate ko library not overriding function property though, cause other unwanted side-effects.
Comments
Post a Comment