user1139190
user1139190

Reputation: 13

Knockoutjs ObservableArray

The following snippet -- results in an empty list-box. Could anyone tell me what am doing wrong?

<script src="/Scripts/knockout-2.1.0.debug.js"></script>
<script type="text/javascript">
var listEditorVM = function () {
    this.allItems = ko.observableArray(["Apple", "Banana", "Orange"]);
    alert(this.allItems().length);
};
ko.applyBindings(new listEditorVM());

</script>

<div>List items:</div>
<select multiple="multiple" data-bind="options: allItems"></select>

Works is jsFiddle -- not in the browser(s)

Upvotes: 0

Views: 337

Answers (1)

RP Niemeyer
RP Niemeyer

Reputation: 114792

You need to call ko.applyBindings after your DOM is ready. You could do this by moving that script block to the bottom of the page or call it in something like jQuery's ready function.

By default, jsFiddle will run your js code "onload", so it will happen after your elements are there.

Upvotes: 3

Related Questions