2012-08-08 2 views
2

제품 객체에 범주 배열 (ID, 이름)이있는 제품의 observablearray가있는 viewmodel이 있다고 가정 해 보겠습니다. 나는 또한 단지 카테고리 인 필터의 관찰 가능한 배열을 가지고있다. 필터가 관찰 가능한 배열에 모든 범주가있는 모든 제품을 찾을 수있는 방법이 있습니까? 따라서 필터 배열에 모든 범주가있는 모든 제품을 반환해야 하나의 필터가 아닌 제품을 반환해야하지만 제품에 모든 필터가 포함되어야합니다. 사전KnockoutJS 필터 ObservableArray 다른 ObservableArry에 의해

답변

3

감사 나는 그것이해야한다고 생각은 다음과 같습니다

 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 코드