简体   繁体   English

KnockoutJS-无容器控制流绑定初始值

[英]KnockoutJS - containerless control flow binding initial value

I have a select control inside which I need to use ko:foreach instead of the usual bindings. 我有一个选择控件,在其中需要使用ko:foreach而不是通常的绑定。 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. 尽管将select控件设置为Option 1,但以下内容中的“ specialProperty”的初始值设置为unknown,所有这些都可以正常工作。 Fiddle here: http://jsfiddle.net/aCS7D/1/ 在这里提琴: 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());​

This is because select is initialized and binding is set but value binding is triggered only when change event fires on select. 这是因为select已初始化并设置了绑定,但是只有在select上触发change事件时才触发value绑定。 The simple fix for this is to add 简单的解决方法是添加

$('select').trigger('change');

after applying bindings. 在应用绑定之后。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM