假设我有以下绑定(bind):
<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>
我想做的是:
- 当选择某个国家/地区时,应自动选中该复选框,并应显示 div 部分。
- 当用户选择不同的国家/地区时,不会自动选中该复选框,但如果用户手动选中该复选框,则应显示该 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。
关于javascript - 基于下拉选择的 knockout 检查绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22184917/