Reputation: 115
Ok I am probably doing something very silly that is preventing me from getting this to work, but here goes anyway:
I am trying to learn how to work with knockout and am trying to build a select list with options defined as an observable array. Here is the code:
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript" src="./knockout-3.0.0.js"></script>
<script type="text/javascript">
var viewModel = {
availableQuestions : ko.observableArray(['Who?', 'What?', 'When?'])
};
ko.applyBindings(viewModel);
</script>
<p>Questions to Ask: <select data-bind="options: availableQuestions"></select></p>
</body>
</html>
This is basically right out of one of their own examples but I cannot get it to work. The select list is not populated at all. I am using the latest version of Chrome (31.0.1650.57) and have looked in developer tools to see if there are issues. I have confirmed that everything is loading properly (ie: knockout is loading, the html is valid) still nothing. Am I missing something obvious?
here is the fiddle:
http://jsfiddle.net/janarde/r9pCK/
EDIT
Thanks to PW Kad It turned out to be that the DOM wasn't loaded before the binding:
EDIT Thanks to Ek0nomik for pointing out the need to put knockout stuff after the markup.
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript" src="./knockout-3.0.0.js"></script>
<script type="text/javascript" src="jquery-1.10.2.min.js"></script>
<p>Questions to Ask: <select data-bind="options: availableQuestions"></select></p>
<script type="text/javascript">
var viewModel = {
availableQuestions : ko.observableArray(['Who?', 'What?', 'When?'])
};
ko.applyBindings(viewModel);
</script>
</body>
</html>
Upvotes: 0
Views: 1760
Reputation: 14995
Are you sure that the DOM is loaded before you are trying to apply bindings?
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="./knockout-3.0.0.js"></script>
</head>
<body>
<p>Questions to Ask: <select data-bind="options: availableQuestions"></select></p>
<script type="text/javascript">
$( document ).ready(function() {
var viewModel = {
availableQuestions : ko.observableArray(['Who?', 'What?', 'When?'])
};
ko.applyBindings(viewModel);
});
</script>
</body>
</html>
Upvotes: 1
Reputation: 25521
You need to make sure you call applyBindings
. Here is a working jsFiddle: http://jsfiddle.net/b4wHQ/
HTML
<p>Questions to Ask: <select data-bind="options: availableQuestions"></select></p>
Javascript
var viewModel = {
availableQuestions : ko.observableArray(['Who?', 'What?', 'When?'])
};
ko.applyBindings(viewModel);
Upvotes: 2