Sorting a Backbone Collection After initialization

后端 未结 4 1894
挽巷
挽巷 2020-12-08 02:27

I am using Backbone.js to render a list of items e.g Books. After the list is rendered, there are options for user to sort them. So if user clicks on Sort By Title, or Sort

4条回答
  •  半阙折子戏
    2020-12-08 02:57

    This way works well and enables sorting by all attributes dynamically and handles ascending or descending:

    var PhotoCollection = Backbone.Collection.extend({
        model: Photo,
        sortByField: function(field, direction){
                sorted = _.sortBy(this.models, function(model){
                    return model.get(field);
                });
    
                if(direction === 'descending'){
                    sorted = sorted.reverse()
                }
    
                this.models = sorted;
        }
    });
    

提交回复
热议问题