KnockoutJS - Binding value of select with optgroup and javascript objects

http://stackoverflow.com/questions/11189660/knockoutjs-binding-value-of-select-with-optgroup-and-javascript-objects

HTML

<script src="http://knockoutjs.com/downloads/knockout-2.2.1.js"></script>
<script src="http://mbest.github.io/knockout-repeat/knockout-repeat.js"></script>
<h2>Multiple selected options</h2>

<select data-bind="selectedOptions: selectedOptions" multiple="multiple">
    <option>Please choose an option</option>
    <optgroup data-bind="repeat: groups" data-repeat-bind="attr: {label: $item().label}">
        <option data-bind="repeat: $item().children" data-repeat-bind="text: $item().label, option: $item()"></option>
    </optgroup>
</select>

<br>Value:
<div data-bind="foreach: selectedOptions">
   <label data-bind="text: label"/>
</div>should be preselected
<br>
<br>
<h3>One selected option</h3>

<select data-bind="value: selectedOption" multiple="multiple">
    <option>Please choose an option</option>
    <optgroup data-bind="repeat: groups" data-repeat-bind="attr: {label: $item().label}">
        <option data-bind="repeat: $item().children" data-repeat-bind="text: $item().label, option: $item()"></option>
    </optgroup>
</select>

</br>Value:
<label data-bind="text: selectedOption.label">
   <span data-bind="text: label"/>
</label>should be preselected

JavaScript

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

function Group(label, children) {
    this.label = ko.observable(label);
    this.children = ko.observableArray(children);
}

function Option(label, property) {
    this.label = ko.observable(label);
    this.someOtherProperty = ko.observable(property);
}

var ViewModel = function() {
    this.groups = ko.observableArray([
        new Group("Group 1", [
            new Option("Option 1", "A"),
            new Option("Option 2", "B"),
            new Option("Option 3", "C")
        ]),
        new Group("Group 2", [
            new Option("Option 4", "D"),
            new Option("Option 5", "E"),
            new Option("Option 6", "F")
        ])
    ]);
    
    //Im retrieving my selected objects directly from the 
    //options array to be sure that they are the same value
    var selected1 = this.groups()[1].children()[1];
    var selected2 = this.groups()[1].children()[0];
    
    //The multiple selected options
    this.selectedOptions = ko.observableArray([ selected1, selected2]);

    //The single selected option
    this.selectedOption = ko.observable(selected1);    
};

ko.applyBindings(new ViewModel());