Knockout Js的多选择绑定



我在KnockoutJs下拉列表中有一个国家列表绑定的集合,如下所示

输入图片描述

在knockoutJS中,如何在所有其他国家/地区列表中删除该国家,只要该国家在一个列表中被选中?

如果您有所有地区,则可以动态确定还剩下哪些国家要选择。逻辑:

  • 收集所有区域及其选择
  • 从列表中删除当前正在查看的区域
  • 选取所有可用的国家
  • 从该列表中删除其他地区选择的任何国家
  • 在代码:

const getAvailableCountries = (allRegions, thisRegion) => {
const otherRegions = allRegions.filter(r => r !== thisRegion);
const inUseByOtherRegions = new Set(
otherRegions.flatMap(r => r.selectedCountries())
);

return countries.filter(c => !inUseByOtherRegions.has(c));
}

困难的部分是获得对"兄弟区域"的引用。我的建议是使用knockout的绑定上下文:

data-bind="options: getAvailableCountries($parent.regions, $data)"

在可运行的示例中:

const countries = [ "C1", "C2", "C3", "C4", "C5" ];
const regions = ["R1", "R2", "R3" ];
const getAvailableCountries = (allRegions, thisRegion) => {
const inUseByOtherRegions = new Set(
allRegions.flatMap(r => r === thisRegion
? []
: r.selectedCountries()
)
);

return countries.filter(c => !inUseByOtherRegions.has(c));
}
const vm = {
regions: regions.map(
regionId => ({
regionId,

getAvailableCountries,
selectedCountries: ko.observableArray([])
})
)
}

ko.applyBindings(vm);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<div data-bind="foreach: regions" style="display: flex; justify-content: space-between;">
<div>
<h2 data-bind="text: regionId"></h2>
<select data-bind="
options: getAvailableCountries($parent.regions, $data),
selectedOptions: selectedCountries" size="5" multiple="true"></select>
</div>
</div>