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

时间:2012-06-25 16:46:43

标签: javascript jquery knockout.js

我有一个select控件,我需要使用ko:foreach而不是通常的绑定。这一切都很完美,除了" specialProperty"的初始值。尽管选择控件设置为选项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());​

1 个答案:

答案 0 :(得分:1)

这是因为select已初始化并且已设置绑定,但仅当value事件在select上触发时才会触发change绑定。对此的简单修复是添加

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

申请绑定后。