Search code examples
knockout.jsko.observablearray

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)


Solution

  • 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.