Knockout with repeat binding: Initially selected value being overwritten

浪尽此生 提交于 2020-01-05 08:52:16

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!