Sorting strings in reverse order with backbone.js

后端 未结 6 2014
南方客
南方客 2020-12-08 07:25

I\'m trying to sort a Backbone.js collection in reverse order. There are previous replies on how to do this with integers, but none with strings.

var Chapter         


        
6条回答
  •  佛祖请我去吃肉
    2020-12-08 07:33

    I just solved a similar problem with table sorting and I wanted to share the code since I didn't find much help in these answers:

    events: {
    
        'click th.sortable': function(e) {
            var $this = $(e.target),
                order = $this.hasClass('asc') ? 'desc' : 'asc',
                field = $this.data('field'); /* this is a string */
    
            $this.siblings().addBack().removeClass('asc desc');
            $this.addClass( order );
    
            this.bodyView.collection.comparator = field;
            this.bodyView.collection.sort();
            if ( order === 'desc' ) this.bodyView.collection.models.reverse();
    
            this.bodyView.render();
        }
    
    },
    

    in this case I simply set comparator to string instead of a function; the string has to be the name of the property you want to sort by. Then I just call reverse on the models if the order has to be inverse.

提交回复
热议问题