Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort computed property on an ArrayController

Tags:

ember.js

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')
});
like image 686
RyanHirsch Avatar asked Jul 18 '13 00:07

RyanHirsch


1 Answers

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.

like image 178
Darshan Sawardekar Avatar answered Nov 01 '22 08:11

Darshan Sawardekar