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

前端 未结 6 1024
孤独总比滥情好
孤独总比滥情好 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:14

    This is what I ended up doing for the app I'm currently working on. In my collection I have:

    comparator: function(model) {
        var methodName = applicationStateModel.get("comparatorMethod"),
            method = this[methodName];
        if (typeof(method === "function")) {
            return method.call(null, model);
        }
    }
    

    Now I can add few different methods to my collection: fooSort(), barSort(), and bazSort().
    I want fooSort to be the default so I set that in my state model like so:

    var ApplicationState = Backbone.Model.extend({
        defaults: {              
            comparatorMethod: "fooSort"
        }
    });
    

    Now all I have to do is write a function in my view that updates the value of "comparatorMethod" depending upon what the user clicks. I set the collection to listen to those changes and do sort(), and I set the view to listen for sort events and do render().

    BAZINGA!!!!

提交回复
热议问题