Knockout.Js selectedOptions从第二个集合中过滤掉

时间:2013-04-13 19:12:02

标签: jquery knockout.js

我将一个集合绑定到一个select multi,集合中的一些项目也在第二个集合中,我想将它们设置为select multi中的selectedOptions。

我希望使用ko.utils.arrayFilter来执行此操作,但似乎无法从另一个集合中过滤一个集合。

http://jsfiddle.net/dumbarse/BcUBK/

<select data-bind="options:availableThings,optionsText: 'Title', selectedOptions: selectedComputeThings" size="5"  multiple="true"></select>
        var initialThingsModel = [
            {"Id":1,"Title":"First"},
            {"Id":2,"Title":"Next"},
            {"Id":3,"Title":"Another"},
            {"Id":4,"Title":"Last"}
        ];
           var initialSelectedThingsModel = [
            {"Id":2,"Title":"Next"},
            {"Id":4,"Title":"Last"}];

    var viewModel = {
        availableThings: ko.observableArray(initialThingsModel),   
        selectedThings:  ko.observableArray(initialSelectedThingsModel)
    };
    viewModel.selectedComputeThings = ko.computed(function() { return ko.utils.arrayFilter(viewModel.availableThings(), function(item) { return item.Id == selectedThings.Id;}) });

        ko.applyBindings(viewModel);

1 个答案:

答案 0 :(得分:1)

你应该修改你的computed并写下这样的内容:

viewModel.selectedComputeThings = ko.computed(function() {
    return ko.utils.arrayFilter(
        initialThingsModel,
        function(thing){ 
            return ko.utils.arrayFirst(
                initialSelectedThingsModel,
                function(sel){ return sel.Id == thing.Id; }
            );
        }
    );
});

作品:http://jsfiddle.net/BcUBK/1/

<强>更新

要跟踪选择,您不需要computed - 只需简单observableArray(哦,你的模型中有selectedThings!)。只需填写参考选项即可。

略微修改您的selectedThings声明:

selectedThings:  ko.observableArray([])

computed转换为将refs分配给selectedThings可观察数组的简单函数:

viewModel.preselectThings = function() {
    viewModel.selectedThings(ko.utils.arrayFilter(
        initialThingsModel,
        function(thing){ 
            return ko.utils.arrayFirst(
                initialSelectedThingsModel,
                function(sel){ return sel.Id == thing.Id; }
            );
        }
    ));
};

ko.applyBindings之前/之后的任何地方添加函数调用:

ko.applyBindings(viewModel);

viewModel.preselectThings();

并在标记的任何位置将selectedComputeThings更改为selectedThings

利润!

http://jsfiddle.net/BcUBK/3/