Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/silverlight/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Knockout.js 带重复绑定的敲除:最初选择的值被覆盖_Knockout.js_Knockout 2.0 - Fatal编程技术网

Knockout.js 带重复绑定的敲除:最初选择的值被覆盖

Knockout.js 带重复绑定的敲除:最初选择的值被覆盖,knockout.js,knockout-2.0,Knockout.js,Knockout 2.0,我有一个selectselectedValue的预设值,该值为“ham”。 我有3个选项“垃圾邮件”、“火腿”、“奶酪” 应用viewmodel时,会选择“ham”值,但selectedValue会松开它的值,因此“ham”虽然看起来是选中的,但实际上不会被选中 我需要更改什么以允许selectValue保留其初始值? 这是我的建议 Html <select data-bind="value:selectedValue"> <option data-bind="repea

我有一个select
selectedValue
的预设值,该值为“ham”。 我有3个选项“垃圾邮件”、“火腿”、“奶酪”

应用viewmodel时,会选择“ham”值,但
selectedValue
会松开它的值,因此“ham”虽然看起来是选中的,但实际上不会被选中

我需要更改什么以允许
selectValue
保留其初始值? 这是我的建议

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>
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());
注意:
我使用的是来自的重复绑定。我通常会使用常规选项绑定,但我需要重复绑定以使选定标签正常工作。

有几种不同的方法可以处理此问题。我认为一个简单的方法是使用一个自定义绑定,首先将绑定应用于它的子级

以下是一个例子:

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 };
    }
};
现在,您可以指定:

<select data-bind="bindChildren: true, value: selectedValue">
    <option data-bind="repeat: values" data-repeat-bind="value: $item(), text: $item()"></option>
</select>


下面是一个示例:

我编辑了它,以便在绑定子体时使用绑定上下文而不是视图模型。这样他们就可以访问
$root
$parent
等。
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 };
    }
};