KnockoutJS - Binding value of select with optgroup and javascript objects

This version with caption and if you want to have parent item selected:

<select data-bind="value: selectedOption ">
    <option data-bind="value:'', text:'Select'"></option>
    <!-- ko foreach: groups -->
        <optgroup data-bind="attr:{label: label}">
            <option data-bind="value: $data, text:label"></option>
            <!-- ko foreach: children -->
                <option data-bind="value: $data, text:label"></option>
            <!-- /ko -->
        </optgroup>
    <!-- /ko -->
</select>

A good choice for this situation is to create a quick custom binding that let's your "hand-made" options behave in the same way as options created by the options binding (attaches the object as meta-data). The binding could simply look like:

ko.bindingHandlers.option = {
    update: function(element, valueAccessor) {
       var value = ko.utils.unwrapObservable(valueAccessor());
       ko.selectExtensions.writeValue(element, value);   
    }        
};

You would use it like:

<select data-bind="foreach: groups, value: selectedOption">
    <optgroup data-bind="attr: {label: label}, foreach: children">
        <option data-bind="text: label, option: $data"></option>
    </optgroup>
</select>

Sample here: http://jsfiddle.net/rniemeyer/aCS7D/