I can't get filterBy to listen


#1

I’m getting really frustrated. This is my entire controller

import Ember from 'ember';

export default Ember.Controller.extend({
    department: 'all',
    level: 'all',
    filteredPosts: Ember.computed.filter('model',  function(item) {
        var lvl = this.get('level');
        if(lvl == 'all') {
            return true;
        }
        else if (lvl == 'intern' && item.level == 'intern') {
            return true;
        } 
        return false;
    }),


    actions: { 
        filterWith(dept, lvl) {
            this.set('department', dept);
            this.set('level', lvl);
        }
    }
});

What I want is for the ‘filteredPosts’ value to recompute whenever the ‘level’ variable is changed. The problem is that I can’t seem to get it to listen for my ‘level’ variable. It only listens to the ‘model’. Does anyone now how I can get this to compute whenever ‘level’ changes?


#2

You need to filter yourself:

filteredPosts: Ember.computed('model.[]', 'level',  function() {
  return this.get('model').filter((item) => {
        var lvl = this.get('level');
        if(lvl == 'all') {
            return true;
        }
        else if (lvl == 'intern' && item.level == 'intern') {
            return true;
        } 
        return false;
  })
}),

#3

Or you could use:

filteredPosts: Ember.computed.filter('model',  function(item) {
    ...
}).property('model', 'level'),

Which I actually prefer. :slight_smile:


#4

I don’t recommend doing that.


#5

@locks - could you explain why not? We’re using that feature heavily, should we abandon it?


#6

Bumping for Boris’s question


#7

I can recommend avoiding .property for code readability. Having all the dependent keys up the top makes it much easy to find what can trigger that computed property. This becomes more important as your code base grows

My guess re locks’ comment is that .property is a hangover from the prototype extension days where function(){}.property() defined a computed property and it’s likely to be deprecated at some stage. It hasn’t been the recommended way since v1.12.0