Ember - 按多个方向的多个属性对数组进行排序

时间:2013-02-21 09:51:24

标签: javascript sorting ember.js

我需要按多个属性对Ember Models的集合进行排序,而不需要在相同的方向/顺序上。即我需要按升序顺序中的属性 a 降序中的属性 b 进行排序。有没有办法实现这个目标?

更新

我尝试将sortAscending属性设置为数组,但它无效。 在查看源代码之后,似乎不支持开箱即用(<)。

3 个答案:

答案 0 :(得分:15)

在您的ArrayController中:

sortProperties: ["propA:asc", "propB:desc"]
sortedModel: Ember.computed.sort("model", "sortProperties");

然后在模板的sortedModel处理程序中引用#each

答案 1 :(得分:5)

我决定创建一个 mixin ,它允许按多个顺序(方向)进行排序。它将SortableMixin扩展到尽可能向后兼容的范围。实际上它可以用作常规SortableMixin。它添加的是sortAscendingProperties属性,它是排序属性名称(sortProperty数组的成员)的数组,应按升序排序。如果属性位于sortAscendingProperties,则将按升序排序,否则将根据sortAscending进行排序,这是默认值。
我把混合调用MultiSortableMixin虽然我认为它不是最好的名字。

(function() {

    var get = Ember.get, set = Ember.set, forEach = Ember.EnumerableUtils.forEach;

    /**
     * extends the SortableMixin by allowing sorting by multiple orders.
     *
     * sortProperties - array of strings
     * sortAscending - default sort order
     * sortAscendingProperties - properties which are listed here will be sorted in ascending order, those which are not listed - will be sorted according to sortAscending
     */
    Ember.MultiSortableMixin = Ember.Mixin.create(Ember.SortableMixin, {
        /**
         Specifies the arrangedContent's sort direction

         @property {Array} sortAscendingProperties
         */
        sortAscendingProperties: null,
        orderBy: function(item1, item2) {
            var result = 0,
                    sortProperties = get(this, 'sortProperties'),
                    sortAscending = get(this, 'sortAscending'),
                    sortAscendingProperties = get(this, 'sortAscendingProperties');

            Ember.assert("you need to define `sortProperties`", !!sortProperties);

            forEach(sortProperties, function(propertyName) {
                if (result === 0) {
                    result = Ember.compare(get(item1, propertyName), get(item2, propertyName));
                    //use default sortAscending if propertyName is not listed in sortAscendingProperties
                    var sa = (sortAscendingProperties && sortAscendingProperties.indexOf(propertyName) > -1) || sortAscending;
                    if ((result !== 0) && !sa) {
                        result = (-1) * result;
                    }
                }
            });

            return result;
        },
        //overrided to add more watched props. TODO - the contents of this method is the same as parent's - find the way to just add watched stuff
        arrangedContent: Ember.computed('content', 'sortProperties.@each', 'sortAscendingProperties.@each', 'sortAscending', function(key, value) {
            var content = get(this, 'content'),
                    isSorted = get(this, 'isSorted'),
                    sortProperties = get(this, 'sortProperties'),
                    self = this;

            if (content && isSorted) {
                content = content.slice();
                content.sort(function(item1, item2) {
                    return self.orderBy(item1, item2);
                });
                forEach(content, function(item) {
                    forEach(sortProperties, function(sortProperty) {
                        Ember.addObserver(item, sortProperty, this, 'contentItemSortPropertyDidChange');
                    }, this);
                }, this);
                return Ember.A(content);
            }

            return content;
        }),
    // unneeded in this mixin, overrided to disable functionality from SortableMixin. TODO - find a way to just remove it
        sortAscendingDidChange: Ember.observer(function() {
            //empty
        }, 'sortAscending')
    });

})();

用法示例:

App.ThingsController = Ember.ArrayController.extend(Ember.MultiSortableMixin, {
    sortProperties: ['prop1', 'prop2', 'prop3'], 
    sortAscending: false,
    sortAscendingProperties: ['prop2', 'prop3'], 
    //your stuff
});

在此示例中,ThingsController的内容将按 prop1 排序 - 按降序排列,然后按 prop2 prop3 排序 - 按升序排列。

答案 2 :(得分:0)

这不是Ember的开箱即用功能。但是查看code of SortableMixin可以看到它使用Ember.compare来比较两个实体:

orderBy: function(item1, item2) {
    var result = 0,
        sortProperties = get(this, 'sortProperties'),
        sortAscending = get(this, 'sortAscending');

    Ember.assert("you need to define `sortProperties`", !!sortProperties);

    forEach(sortProperties, function(propertyName) {
      if (result === 0) {
        result = Ember.compare(get(item1, propertyName), get(item2, propertyName));
        if ((result !== 0) && !sortAscending) {
          result = (-1) * result;
        }
      }
    });

    return result;
  },

Ember.compare包含对Comparable Mixin

的检查
var Comparable = Ember.Comparable;
  if (Comparable) {
    if (type1==='instance' && Comparable.detect(v.constructor)) {
      return v.constructor.compare(v, w);
    }

    if (type2 === 'instance' && Comparable.detect(w.constructor)) {
      return 1-w.constructor.compare(w, v);
    }
  }

因此我建议的解决方案是:

1 - 在模型中添加一个附加字段,其中包含所有sortingProperties的包装器对象,例如“combinedAandB”

App.YourModel = Ember.Object.extend({
a : null,
b : null,
combinedAandB : function(){
  // the following Object should implement SortableMixin
  var comparator = App.AandBComparator.create(this.get("a"), this.get("b"));
  return comparator;
}.property("a","b")

2 - 您的ComparatorModel(App.AandBComparator)应该实现Comparable Mixin。在这个比较方法中,尊重你想要的排序行为(支持升序和道具降序)。

3 - 现在您可以实例化一个ArrayController并根据您的组合属性对其进行排序:

var yourModelController = //whereever you may get that one from
yourModelController.set("sortProperties", "combinedAandB");

注意:这只是我在阅读您的要求时得到的一个自发的想法。我还没有实现这一点。所以这可能并不完美: - )