Reverse sort order with Backbone.js

前端 未结 15 1002
不知归路
不知归路 2020-12-02 05:45

With Backbone.js I\'ve got a collection set up with a comparator function. It\'s nicely sorting the models, but I\'d like to reverse the order.

How can I sort the m

15条回答
  •  孤街浪徒
    2020-12-02 06:10

    I had a slightly different requirement, in that I am displaying my models in a table, and I wanted to be able to sort them by any collumn (model property) and either ascending or descending.

    It has taken a fair amount of mucking around to get all the cases working (where values can be strings, empty strings, dates, numbers. However I think this is pretty close.

        inverseString: function(str)
        {
            return str.split("").map(function (letter) { return String.fromCharCode(-(letter.charCodeAt(0))); }).join("");
        }
        getComparisonValue: function (val, desc)
        {
            var v = 0;
            // Is a string
            if (typeof val === "string")
            {
                // Is an empty string, upgrade to a space to avoid strange ordering
                if(val.length === 0)
                {
                    val = " ";
                    return desc ? this.inverseString(val) : val;
                }                
    
                // Is a (string) representing a number
                v = Number(val);
                if (!isNaN(v))
                {
                    return desc ? -1 * v : v;
                }
                // Is a (string) representing a date
                v = Date.parse(val);
                if (!isNaN(v))
                {
                    return desc ? -1 * v : v;
                }
                // Is just a string
                return desc ? this.inverseString(val) : val;
            }
            // Not a string
            else
            {
                return desc ? -1 * val : val;
            }
        },
    

    use:

        comparator: function (item)
        {
            // Store the collumn to 'sortby' in my global model
            var property = app.collections.global.get("sortby");
    
            // Store the direction of the sorting also in the global model
            var desc = app.collections.global.get("direction") === "DESC";
    
            // perform a comparison based on property & direction
            return this.getComparisonValue(item.get(property), desc);
        },
    

提交回复
热议问题