Reputation: 3897
I have a select control inside which I need to use ko:foreach instead of the usual bindings. It all works perfectly, except the initial value for "specialProperty" in the below is set to unknown, despite the select control being set to Option 1. When you manually select an option from the list, it behaves as expected. Fiddle here: http://jsfiddle.net/aCS7D/1/
<select data-bind="value: selectedOption">
<!-- ko foreach:groups -->
<optgroup data-bind="attr: {label: label}, foreach: children">
<option data-bind="text: label, option: $data"></option>
</optgroup>
<!-- /ko -->
</select>
<div data-bind="text: specialProperty"></div>
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")
])
]);
this.selectedOption = ko.observable();
this.specialProperty = ko.computed(function(){
var selected = this.selectedOption();
return selected ? selected.someOtherProperty() : 'unknown';
}, this);
};
ko.applyBindings(new ViewModel());
Upvotes: 0
Views: 189
Reputation: 56467
This is because select
is initialized and binding is set but value
binding is triggered only when change
event fires on select. The simple fix for this is to add
$('select').trigger('change');
after applying bindings.
Upvotes: 1