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);
?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…