I'm trying to manually render options inside of optgroups in knockout.js with guidance from Ryan Niemeyer's answer here. It works fine, but only if the options are rendered immediately. If they're loaded subsequently, then the correct item does not select.
The code and fiddle link are below. Changing
t: ko.observable(null)
to
t: ko.observable(t)
makes it work, so the problem is definitely the delayed loading, and I have valueAllowUnset set to true.
fiddle: http://jsfiddle.net/exyy7hq2/3/
HTML
<select data-bind="template: { name: 'selectTemplateType', data: t }, valueAllowUnset: true, value: selectedId"></select>
<div data-bind='text: selectedId'></div>
<script type="text/html" id="selectTemplateType">
<!-- ko ifnot: $data -->
<option>No template selected</option>
<!-- /ko -->
<!-- ko if: $data -->
<option>Select</option>
<!-- ko foreach: groups -->
<optgroup data-bind="attr: { 'label': name }, foreach: types">
<option data-bind="option: id, text: name"></option>
</optgroup>
<!-- /ko -->
<!-- /ko -->
</script>
JavaScript
ko.bindingHandlers.option = {
update: function(element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
ko.selectExtensions.writeValue(element, value);
}
};
var t = {
groups: [
{ name: 'a', types: [{id: 1, name: 't1'}] },
{ name: 'b', types: [{id: 102, name: 't2'}, {id: 103, name: 't3'}] },
{ name: 'c', types: [{id: 5, name: 'x'}] }
]
}
var vm = {
t: ko.observable(null),
selectedId: ko.observable(103)
};
ko.applyBindings(vm);
setTimeout(function(){ vm.t(t); }, 2000);