EmberJS How build a dynamic filtering


#1

I have a list of items which can be sorted, filtered and queried.

Sort them is quite easy:

var ToDoList = Ember.Object.extend({
  // using standard ascending sort
  todosSorting: ['name:desc'],
  sortedTodos: Ember.computed.sort('todos', 'todosSorting')
});

Then you can easily change the value of todosSorting to e.g. ['name:asc'] or the name of each todo. The EmberJS Magic will sort everything. You can even change todosSorting to another attribute of todos, it just works.

Filtering seems less powerful. You can either give a function or a key plus value. It’s not so powerful as sort. You can change the filtered property of each todo and the list will be filtered. But how to change the value or the key of the filter?

Is there a way to achieve the same level of flexibility like with .sort()?

e.g.:

var ToDoList = Ember.Object.extend({
  todosFilteringKey: 'priority',
  todosFilteringValue: 1,
  filteredTodos: Ember.computed.filter('todos', 'todosFilteringKey', 'todosFilteringValue')
});

At the moment I achieve it this way:

var ToDoList = Ember.Object.extend({
  currentFilter: 'all',
  filterBy: Ember.computed('currentFilter', function() {
    return this.filters[this.get('currentFilter')];
  }),

  filters: {
    all: function(item) {
      return true;
    },

    priority1: function(item) {
      return item.get('priority') === 1;
    },

    priority2: function(item) {
      return item.get('priority') === 2;
    },
  }

  filteredTodos: Ember.computed('todos', 'filterBy', 'todos.@each.priority', function () {
    return this.filter();
  }),

  filter: function() {
    return this.get('todos').filter(function(todo) {
      return this.get('filterBy')(todo);
    }.bind(this));
  },
});

This does not scale well if you have multiple filtering possibilities


#2

I use ember-cli-filter-by-query with the sort false option.

See: