I found an example here to create a select list with optgroups using KnockoutJS. This works fine, but I want to bind the value of the dropdown to my own javascript object, then access a particular property of that object:
<select data-bind="foreach: groups, value:selectedOption">
<optgroup data-bind="attr: {label: label}, foreach: children">
<option data-bind="text: label"></option>
</optgroup>
</select>
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 = {
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")
])
]),
selectedOption: ko.observable(),
specialProperty: ko.computed(function(){
this.selectedOption().someOtherProperty();
})
};
ko.applyBindings(viewModel);
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:You would use it like:
Sample here: http://jsfiddle.net/rniemeyer/aCS7D/
If you want to have full control over the caption, groups and options and make this work with the value binding on the select element, you'll have to make sure all the options are bound before the select's value binding is bound. Otherwise the value binding will empty the selectedOption observable once the caption option is added.
You could for example add a custom
valueAfterChildren
binding, which wraps the value binding and makes sure the children are bound first. Have a look at the example below, which pre-selects "Option 5" on the slightly simplified viewmodel, before applying the bindings:This version with caption and if you want to have parent item selected: