Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

arrays - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...