Sort content of ArrayController

arrays, ember.js, sorting

Solution

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()
});

Problem

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.

Original source

Related problems