6

I have the following jsbin: http://jsbin.com/okoxim/4/edit

filteredContent is a computed property which is filtering my Controller's content. I want to know how to sort the computed property and any ways I can improve the code I have.

App.StudentsController = Ember.ArrayController.extend({
  sortProperties: ['name'],
  nameFilter: null,
  filteredContent: function(){
    if(!this.get('nameFilter')) return this.get('content');

    var nameRegEx = new RegExp(this.get('nameFilter'), 'i');
    return this.filter(function(item) {
      return item.get('name').search(nameRegEx) !== -1;
    });
  }.property('nameFilter', '@each.name')
});

1 Answer 1

8

Easiest way is to wrap the result in an ArrayProxy which sorts on the same sortProperties values. Something like,

filteredContent: function(){
  var result;

  if (!this.get('nameFilter')) {
    result = this.get('content');      
  } else {
    var nameRegEx = new RegExp(this.get('nameFilter'), 'i');
    result = this.filter(function(item) {
      return item.get('name').search(nameRegEx) !== -1;
    });
  }

  var sortedResult = Em.ArrayProxy.createWithMixins(
    Ember.SortableMixin, 
    { content:result, sortProperties: this.sortProperties }
  );

  return sortedResult;
}.property('nameFilter', '@each.name')

Here's the updated jsbin.

Another way is to make filteredContent an explicit ArrayProxy and filter/sort on that.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.