-1

I am trying to sort my collection using .sort() however I can only seem to sort the collection in an ascending manner, by code for the collection is like this,

    var ProjectCollection = Backbone.Collection.extend({

    url: '/projects',
    model: app.Project,
    sort_key: "finish_date",

    comparator: function (item) {
        return item.get(this.sort_key);
    },

    sortByField: function(fieldName, orderType) {
        console.log(fieldName, orderType);
        this.sort_key = fieldName;
        if(orderType == "acsending") {
            this.sort(function(a, b){return a-b});
        } else if(orderType == "descending") {
            this.sort(function(a, b){return b-a});
        }
    }

});

The sortByField function gets fired from the view on a select menu change, and it fires this function,

sortCollection: function(e) {

        this.collection.sortByField($('.sort').val(), $('.order').val());
        console.log(this.collection);

    }

Why would I not be able to sort in a descending order? The parameters that get sent to the collections function are correct, and the if and if else are run correctly based on those params.

DJ Burb
  • 2,346
  • 2
  • 29
  • 38
Udders
  • 6,914
  • 24
  • 102
  • 194

2 Answers2

0

You should use sortBy() method instead of sort().

As explained in the documentation, sort() method just re-sorts the collection (as it does every time when a new model is inserted) and emits 'sort' event.

sortBy() method accepts the function Comparator that will define the order (as in your example) (documentation). Consider that instead of writing

function(a, b){return a-b}

you should write something like this

function(a, b){return a.get("field")-b.get("field")}

This way you compare objects's fields instead of the result of object's toValue() method.

Mironor
  • 1,157
  • 10
  • 25
0

Your models aren't sorted in a descending order because sort() does not accept the comparator callback (see sortBy() in the docs)

You need to put your logic in the comperator() - see this example: http://jsbin.com/petetiwiqo/1/edit?html,js,output

fr00t
  • 681
  • 1
  • 4
  • 19