Knockout Binding不使用foreach选项更新

时间:2014-01-29 10:18:57

标签: javascript knockout.js binding

我有两个选项,秒选项选项取决于第一个选择。

两个选择框都需要附加一个类,所以我不能使用options属性。我发现这样做的唯一方法是使用foreach方法。

我需要随时跟踪两个选定的值,但第二个选择在重新填充新数据时不会更新其值。请看小提琴。

另一个要求是,如果通过viewmodel创建为第二个选择传入的原始选项存在,我希望它在填充时是默认值。例如,当从WPA-PSK更改为无,然后返回时,我希望默认选择为MIX(传入)而不是AES。

小提琴:Link to Fiddle

function ViewModel(security) {
        var self = this;

        self.authenticationMode = ko.observable(security.authenticationMode);
        self.encryptionType = ko.observable(security.encryptionType);

        self.authenticationModes = ko.observableArray([{translationText: "None", mode: "NONE", translationClass: "T_WPA-PSK"},
                                    {translationText: "Open", mode: "OPEN", translationClass: "T_WPA-PSK"},
                                    {translationText: "WPA-PSK", mode: "WPA-PSK", translationClass: "T_WPA-PSK"}]);

        self.encryptionTypes = ko.computed(function () {
            console.log(self.authenticationMode());
            if (self.authenticationMode() === 'OPEN') 
                return [{translationText: "WEP", type: 'WEP', translationClass: "T_WEP"}];
            if (self.authenticationMode() === 'WPA-PSK') 
                return [{translationText: "AES", type: 'AES', translationClass: "T_AES"},
                       {translationText: "MIX", type: 'MIX', translationClass: "T_MIX"}];
            return [];
        });
    }

    ko.applyBindings(new ViewModel({authenticationMode: 'WPA-PSK', encryptionType: 'MIX'}));


<select data-bind="value: authenticationMode, foreach: authenticationModes">
     <option data-bind="text: translationText, value: mode, attr: { class: translationClass }"></option>
</select>

<select data-bind="value: encryptionType, foreach: encryptionTypes">
     <option data-bind="text: translationText, value: type, attr: { class: translationClass }"></option> 
</select>

<p>Selected Authentication: <b data-bind="text:authenticationMode"></b></p>
<p>Selected Encryption Type: <b data-bind="text:encryptionType"></b></p>

Fiddle Using Options - 我发现使用options使用optionsAfterRender方法设置类的另一种方法。

1 个答案:

答案 0 :(得分:1)

更新了你的小提琴:

http://jsfiddle.net/fS8qp/7/

通过在viewmodel中添加以下内容来满足这两个要求:

self.defaultEncryptionType = security.encryptionType;

self.authenticationMode.subscribe(function () {
    self.encryptionType(self.defaultEncryptionType); // This will select the passed in encryptionType, if it exists in the current list of options
    self.encryptionType.valueHasMutated(); // This will trigger an update of the observable
});