ArrayController排序内容 [英] Sort content of ArrayController

查看:169
本文介绍了ArrayController排序内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Ember.ArrayController ,有一个排序的内容。

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

我想知道,如果它可以不使用新属性的ArrayController的内容进行排序。

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.

推荐答案

更新

Ember公司的最新版本实际上已经排序内置的。 ArrayController 现在包括 Ember.SortableMixin 这将参与如果指定 sortProperties (阵列)以及可选 sortAscending (布尔)。

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

注:与新SortableMixin,你仍然需要参考 arrangedContent 来获取排序的版本。该模型本身将保持不变。 (感谢乔纳森陈)

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

原来的答案

要做到这一点,正确的方法是使用ArrayProxy的 arrangedContent 属性。此属性旨在覆盖,以提供内容数组的排序或筛选的版本。

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

这篇关于ArrayController排序内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆