0

我有一个选择控件,我需要在其中使用 ko:foreach 而不是通常的绑定。尽管选择控件设置为选项 1,但下面的“specialProperty”的初始值设置为未知,这一切都很完美。当您从列表中手动选择一个选项时,它的行为与预期一样。在这里小提琴: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());​
4

1 回答 1

1

这是因为select已初始化并设置value了绑定,但仅当change事件在 select 上触发时才触发绑定。解决此问题的简单方法是添加

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

应用绑定后。

于 2012-06-25T16:57:13.850 回答