2

Ember.SortableMixin

自然排序

4

4 回答 4

3

我在我的项目中所做的是覆盖 mixin 的 orderBy 函数(https://github.com/emberjs/ember.js/blob/master/packages/ember-runtime/lib/mixins/sortable.js #L52)并将 Ember.compare() 替换为这种自然排序算法:https ://github.com/overset/javascript-natural-sort

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

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

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

  return result;
}

我做了一个 PR,以便更容易在 sortable mixin 中插入任何排序功能,但它已关闭。在此处查看详细信息:

https://github.com/emberjs/ember.js/pull/1216 https://github.com/emberjs/ember.js/pull/1562

于 2013-03-02T14:09:30.150 回答
2

您必须定义额外的“自然”属性

App.Group = DS.Model.extend                                  
  name: DS.attr 'string'                                             
  natural_name: ( ->                                                
    # Split string into numeric and non-numeric parts
    # and convert numeric parts to actual numbers
    # Sort by resulting array of strings and numbers
    @get('name').split(/([0-9]+)/g).map (str) =>                     
      if str.match(/[0-9]+/) then parseInt(str, 10) else str         
  ).property('name')    



App.GroupsIndexController = Ember.ArrayController.extend
  sortProperties: ['natural_name']
于 2013-02-27T21:18:16.523 回答
1

如果你想使用 SortableMixin,你可以这样做:

childrenSorted: function() {
  return Ember.ArrayProxy.createWithMixins(Ember.SortableMixin, {
    sortProperties: ['name'],
    content: this.get('model.children')
  });
}.property('model.children.@each.name')
于 2013-03-01T02:09:57.017 回答
0

从 Ember Data 1.0(可能更早)开始,您可能希望使用Ember.computed.sort

http://emberjs.com/api/#method_computed_sort

于 2013-09-23T00:07:37.573 回答