【问题标题】:How to sort in natural order with Ember.js SortableMixin?如何使用 Ember.js SortableMixin 按自然顺序排序?
【发布时间】:2013-02-27 20:55:27
【问题描述】:

【问题讨论】:

    标签: javascript sorting ember.js natural-sort


    【解决方案1】:

    我在我的项目中所做的是覆盖 mixin (https://github.com/emberjs/ember.js/blob/master/packages/ember-runtime/lib/mixins/sortable.js#L52) 的 orderBy 函数并将 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

    【讨论】:

      【解决方案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']
      

      【讨论】:

        【解决方案3】:

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

        childrenSorted: function() {
          return Ember.ArrayProxy.createWithMixins(Ember.SortableMixin, {
            sortProperties: ['name'],
            content: this.get('model.children')
          });
        }.property('model.children.@each.name')
        

        【讨论】:

          【解决方案4】:

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

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

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2021-12-16
            • 2017-11-17
            • 2023-03-20
            • 2013-01-07
            相关资源
            最近更新 更多