Search code examples
ember.jsfilterember-datacomputed-properties

Ember 2, Handle two or more properties in just one computed property. How to filter by search text and category


My code is here:

https://ember-twiddle.com/b894cec64a1d78a71e15b642d512cfcf

I need to use this computed property: "postsFiltered" with both Category and Search but when I change category on clickCategory() I need to reset the search text (if present).

But then the computed property is already called? No?

And the same when I search something I need to reset category to null.

postsFiltered: Ember.computed('category', 'search', function () {

var posts = this.get('posts');
var search = this.get('search');

console.log('computed postsFiltered() with category: ' + this.get('category') + ', search: ' + search);
return posts.filter((item) => item['categoryId'] === this.get('category'));

// or this when I search, but I don't know how to do one or the other:
// return posts.filter((item) => item['name'].includes(search));
})

How to handle two properties in the same computed property?


Solution

  • You need to introduce search:'', in controller, and pass it down to posts component {{my-posts posts=posts category=category search=search}} and your clickCategory should reset search property when category clicked

    clickCategory(categoryId) {
       this.set('category', categoryId);
       this.set('search','');
    }
    

    This will ensure that you are following Data Down Actions Up strategy. twiddle

    Edit:

    1. Ember.computed.filterBy here the last argument is an value not the property name
    2. Ember.computed.filter We can't use it either since we need to include one more dependancy toocategory
    3. So finally implemented our own computed property instead inbuilt macros,
        categoryPosts: Ember.computed('posts.[]','category', function(){ 
          return this.get('posts').filter(post => post.categoryId === this.get('category'));
        }),