Sorting a Backbone Collection After initialization

后端 未结 4 1886
挽巷
挽巷 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:43

    There's a discussion on this very topic that you might want to look at: https://github.com/documentcloud/backbone/issues/41.

    The short of it is that when a user selects 'sort by X', you can:

    1. Set the comparator function on the Collection
    2. Call the Collection's sort function (which will trigger a sort event)
    3. Listen for the sort event in your View, and (clear and) redraw the items

    Another way to handle steps 1 & 2 is to have your own method that calls the Collection's sortBy method and then triggers a custom event that your View can listen to.

    But it seems to be the case that clearing and redrawing is the easiest (and maybe even the fastest) way to sort your View's and keep them in sync with your Collection's sort order.

    0 讨论(0)
  • 2020-12-08 02:44

    comparator is what you need

    var PhotoCollection = Backbone.Collection.extend({
        model: Photo,
        comparator: function(item) {
            return item.get('pid');
        }
    });
    
    0 讨论(0)
  • 2020-12-08 02:48

    You can update the comparator function and then call the sort method.

    // update comparator function
    collection.comparator = function(model) {
        return model.get('name');
    }
    
    // call the sort method
    collection.sort();
    

    The view will be automatically re-rendered.

    0 讨论(0)
  • 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;
        }
    });
    
    0 讨论(0)
提交回复
热议问题