繁体   English   中英

Knockout根据下拉选择检查绑定

[英]Knockout checked binding based on drop down selection

说我有以下绑定:

<p>blah blah<input type="checkbox" data-bind="checked: shouldShow" /></p>
 <div data-bind="visible: shouldShow ">...</div>    
 <select data-bind="options: availableCountries,
                       optionsText: 'countryName',
                       value: selectedCountry,
                       optionsCaption: 'Choose...'">
 </select>

我想做的是:

  1. 选择某个国家/地区时,应自动选中该复选框,并显示div部分。
  2. 当用户选择其他国家/地区时,不会自动选中该复选框,但如果用户手动选中该复选框,则应显示该div。

我有以下内容

 shouldShow = ko.computed(function() {                
                if(selectedCountry == 'UK') 
                    return true;
                else
                    return false;
             }, this);

现在这适用于1,但如果用户选择其他国家/地区,并且当用户选中该复选框时,则不会发生任何事情。 我该如何解决?

如果我正确理解了这些要求,手动订阅可能适用于此方案。

您可以使shouldShow成为可观察对象,然后针对selectedCountry创建手动订阅,以确定是否应更新shouldShow 这允许shouldShow独立于国家维护一个值。

this.shouldShow = ko.observable();

this.selectedCountry = ko.observable();

this.selectedCountry.subscribe(function(newValue) {
    this.shouldShow(newValue === "UK");
}, this);

更改国家/地区后,将更新复选框。 但是,如果用户选中该框,它仍会将其设置为true。

暂无
暂无

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

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