0

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?

2
  • 2
    How are you accessing it to get the array of zero length ? anotherObservableArray().length should work Commented Feb 19, 2013 at 7:36
  • Yup Thanks.. I was thinking about the js array Commented Feb 19, 2013 at 7:44

2 Answers 2

3

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/

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.