【问题标题】:KnockoutJS Filter ObservableArray by another ObservableArryKnockoutJS 通过另一个 ObservableArry 过滤 ObservableArray
【发布时间】:2012-08-08 14:19:23
【问题描述】:

假设我有一个视图模型,其中包含一个可观察的产品数组,该数组在产品对象上有一个类别数组(Id、Name)。然后我还有一个可观察的过滤器数组,它们只是类别。有没有一种方法可以找到所有在过滤器可观察数组中具有所有类别的产品。因此,我需要返回具有过滤器数组中所有类别的所有产品,而不仅仅是一个过滤器,但该产品必须包含所有过滤器。提前致谢

【问题讨论】:

    标签: knockout.js knockout-2.0


    【解决方案1】:

    我觉得应该是这样的:

            function Product(id, name) {
                this.id = id;
                this.name = name;
                this.categories = [];
            }
    
            function ProductCategory(name) {
                this.name = name;
            }
    
            function ViewModel() {
                this.products = ko.observableArray();
                this.filters = ko.observableArray();
                var self = this;
    
                //dummy data
                self.init = function () {
                    var c1 = new ProductCategory('Cat1');
                    var c2 = new ProductCategory('Cat2');
                    var c3 = new ProductCategory('Cat3');
                    var c4 = new ProductCategory('Cat4');
    
                    var p1 = new Product(1, 'Prod 1');
                    p1.categories = [c1, c2];
    
                    var p2 = new Product(2, 'Prod 2');
                    p2.categories = [c1, c3, c4];
    
                    var p3 = new Product(3, 'Prod 3');
                    p3.categories = [c3, c4];
    
                    var p4 = new Product(4, 'Prod 4');
                    p4.categories = [c1, c2, c4];
    
                    self.products([p1, p2, p3, p4]);
                    self.filters([c1, c3, c4]);
                };
    
                self.init();
    
                //filtered products will be recalculated on products or filters array change
                self.filteredProducts = ko.computed(function () {
                    var filteredProducts = [];
                    ko.utils.arrayForEach(self.products(), function (product) {
                        var notInFilter = false;
    
                        for (var i = 0; i < product.categories.length; i++) {
                            var category = product.categories[i];
    
                            if (self.filters().indexOf(category) < 0) {
                                notInFilter = true;
                                break;
                            }
                        }
    
                        if (!notInFilter) {
                            filteredProducts.push(product);
                        }
                    });
    
                    return filteredProducts;
                });
            }
    

    Fiddle 带代码

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-06
      • 1970-01-01
      • 2012-04-03
      • 1970-01-01
      • 1970-01-01
      • 2021-10-30
      • 1970-01-01
      相关资源
      最近更新 更多