问题
I have a preset value for a select selectedValue
which has a value of "ham".
I have 3 options "spam", "ham", "cheese".
When the viewmodel is applied, the "ham" value is selected, but the selectedValue
looses it's value, so "ham" isn't actually selected although it appears to be.
What do I need to change to allow for selectValue
to retain it's initial value?
Here's the jsfiddle
Html
<select data-bind="value:selectedValue">
<option data-bind="repeat: values"
data-repeat-bind="value: $item(), text: $item()">
</option>
</select>
<br>selectedValue: <span data-bind="text:selectedValue"></span>
ViewModel
var viewModel = function () {
this.selectedValue = ko.observable("ham"); //initial value has been chosen.
this.values = ko.observableArray(["spam", 'ham', 'cheese']);
this.showMeSelectedValue = function(){alert(this.selectedValue())};
};
ko.applyBindings(new viewModel());
Note: I am using the repeat binding from https://github.com/mbest/knockout-repeat. I would usually use the regular options binding, but I need to repeat binding for select labels to work.
回答1:
There are a few different ways that you could handle this one. I think that an easy way would be to use a custom binding that applies binding to its children first.
Here is an example:
ko.bindingHandlers.bindChildren = {
init: function(element, valueAcessor, allBindings, vm, bindingContext) {
//bind children first
ko.applyBindingsToDescendants(bindingContext, element);
//tell KO not to bind the children itself
return { controlsDescendantBindings: true };
}
};
Now, you would specify:
<select data-bind="bindChildren: true, value: selectedValue">
<option data-bind="repeat: values" data-repeat-bind="value: $item(), text: $item()"></option>
</select>
Here is an example: http://jsfiddle.net/rniemeyer/r9kPm/
来源:https://stackoverflow.com/questions/18256618/knockout-with-repeat-binding-initially-selected-value-being-overwritten