Proper way to sort a backbone.js collection on the fly

前端 未结 6 996
孤独总比滥情好
孤独总比滥情好 2021-01-30 02:31

I can successfully do this:

App.SomeCollection = Backbone.Collection.extend({
  comparator: function( collection ){
    return( collection.get( \'lastName\' ) );         


        
6条回答
  •  囚心锁ツ
    2021-01-30 03:03

    This is an old question but I recently had a similar need (sort a collection based on criteria to be supplied by a user click event) and thought I'd share my solution for others tackling this issue. Requires no hardcoded model.get('attribute').

    I basically used Dave Newton's approach to extending native JavaScript arrays, and tailored it to Backbone:

    MyCollection = Backbone.Collection.extend({
    
        // Custom sorting function.
        sortCollection : function(criteria) {
    
            // Set your comparator function, pass the criteria.
            this.comparator = this.criteriaComparator(criteria);
            this.sort();
        },
    
        criteriaComparator : function(criteria, overloadParam) {
    
            return function(a, b) {
                var aSortVal = a.get(criteria);
                var bSortVal = b.get(criteria);
    
                // Whatever your sorting criteria.
                if (aSortVal < bSortVal) {
                    return -1;
                }
    
                if (aSortVal > bSortVal) {
                    return 1;
                }
    
                else {
                    return 0;
                }
    
            };
        } 
    
    });
    

    Note the "overloadParam". Per the documentation, Backbone uses Underscore's "sortBy" if your comparator function has a single param, and a native JS-style sort if it has two params. We need the latter, hence the "overloadParam".

提交回复
热议问题