如何使用foreach绑定将select选项中的参数传递给触发器和筛选数组可观测值

How to pass an argument from select options to trigger and filter array observables using foreach binding

本文关键字:触发器 筛选 数组 可观 参数传递 绑定 foreach 何使用 select 选项      更新时间:2023-09-26

在下面的标记中,我绑定了包含大陆列表的唯一数据:我还订阅了所选值,并与用户选择的大陆触发了一个事件。

<div id="country-collection">
    <select data-bind="options: UniqueContinent,
    value: SelectedContinent"></select>
</div>

代码:

    self.CountryData = ko.observableArray([]);
    self.SelectedContinent = ko.observable('');
    self.UniqueContinent = ko.dependentObservable(function() {
        var continent = ko.utils.arrayMap(self.CountryData(),
            function(item){
                return item.Continent
            })
        return ko.utils.arrayGetDistinctValues(continent).sort();
    });

每次进行选择时都会触发以下功能:

    self.SelectedContinent.subscribe(function (selectedValue) {
      // alert(selectedValue);
    });

使用上面的代码,我需要在以下列表中填充基于默认大陆onload或选定大陆的所有国家:因此,如果选择了亚洲,则显示的唯一国家是亚洲国家及其各自的详细信息。

<div id="country-list">
    <ul data-bind= "foreach: CountryData">
        <li><span data-bind="text: Country"></span></li>
        // More list stuff here (removed for brevity)
    </ul>
</div>

我试过了,但只有当值被硬编码时,它才有效。我需要根据默认值或选择选项的选定值加载国家:

    self.SelectedContinent.subscribe(function (selectedValue) {
        // Call this function when changes are made
        self.FilteredEntries = ko.computed(function() {
            return ko.utils.arrayFilter(self.CountryData(), function(item) {
                // I need to use the selected value
                return item.Continent === 'SOUTH AMERICA';
        });
    });
});

您可以删除订阅函数:

    // Call this function when changes are made
    self.FilteredEntries = ko.computed(function() {
        return ko.utils.arrayFilter(self.CountryData(), function(item) {
            // I need to use the selected value
            return item.Continent === self.SelectedContinent();
        });
    });

使用subscribe,每次选择更改时都会创建一个新的计算可观测值,并且重新分配的计算可观察值从未绑定到DOM。

你可以看看这个小提琴的工作演示。

您可以使用awsome Knockout Projections插件,在这里提供;淘汰预测。

定义过滤后的可观察阵列非常简单,并且实现非常高效:

var FilteredCountries = self.CountryData().filter(
   function(c) { return c.Continent === self.SelectedContinent(); 
});