Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort content of ArrayController

I have a Ember.ArrayController that has an unsorted content.

I want to know if its possible to sort the content of an ArrayController without using a new property.

I could of course create a new property:

App.MyArrayController = Em.ArrayController.extend({
  mySortMethod: function(obj1, obj2) {
    // some code here
  },
  updateSortedContent: function() {
    var content = this.get('content');
    if (content) {
      var sortedContent = content.copy();
      sortedContent.sort(this.mySortMethod);
      this.set('sortedContent', sortedContent);
    }
  }.observes('content')
});

But I hope there is a better way that does not duplicates the content.

like image 846
louiscoquio Avatar asked May 08 '12 12:05

louiscoquio


1 Answers

UPDATE

The latest version of Ember actually has sorting built in. ArrayController now includes the Ember.SortableMixin which will engage if you specify sortProperties (Array) and optionally sortAscending (Boolean).

Note: with the new SortableMixin, you still need to refer to arrangedContent to get the sorted version. The model itself will be left untouched. (Thanks to Jonathan Tran)

App.userController = Ember.ArrayController.create({
  content: [],
  sortProperties: ['age'],
  sortAscending: false
})

ORIGINAL ANSWER

The correct way to do this is to use the arrangedContent property of ArrayProxy. This property is designed to be overridden to provide a sorted or filtered version of the content array.

App.userController = Ember.ArrayController.create({
  content: [],
  sort: "desc",
  arrangedContent: Ember.computed("content", function() {
    var content, sortedContent;
    content = this.get("content");
    if (content) {
      if (this.get("sort") === "desc") {
        this.set("sort", "asc");
        sortedContent = content.sort(function(a, b) {
          return a.get("age") - b.get("age");
        });
      } else {
        this.set("sort", "desc");
        sortedContent = content.sort(function(a, b) {
          return b.get("age") - a.get("age");
        });
      }
      return sortedContent;
    } else {
      return null;
    }
  }).cacheable()
});
like image 114
Ivan Avatar answered Sep 19 '22 06:09

Ivan