I’m fairly new to Knockout.js, so this might be a stupid question.
I’m reading through the Bindings documentation, and particularly the options binding. It says that when applying the binding:
Any previous options will be removed.
Is there a way to preserve the existing options?
<select data-bind="options: availableOptions, optionsText: 'name', value: selectedOption">
<option value="1">One</option>
<option value="2" selected>Two</option>
</select>
<script type="text/javascript">
var option = function(name, value) {
this.name = name;
this.value = value;
};
var viewModel = {
availableOptions : ko.observableArray([]),
selectedOption : ko.observable()
};
</script>
Based on Niko’s suggestion, I guess the answer is that it’s best to avoid mixing declarative bindings with static data. If the view is unlikely to change, put the data in the view (option elements on the select). If it’s dynamic, put the data into the KO viewmodel.
In my scenario it’s the former: