Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8335961
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 9, 20262026-06-09T03:50:08+00:00 2026-06-09T03:50:08+00:00

The desired functionality I’m using a Backbone.Collection to view data in a sortable list.

  • 0

The desired functionality

I’m using a Backbone.Collection to view data in a sortable list. I’ve got the part down where clicking on certain dom elements sets properties on my Collection to determine which field i’d like to sort, and which direction the sort should be done.
A sort should then be triggered on the Collection after which the view will update.

Eventually I want to be able to sort numerical fields as well strings. Some strings should sort alphabetically, others by a custom predefined order.

My current approach

I’ve found the following post on reverse sorting strings:
Sorting strings in reverse order with backbone.js

I tried to combine this with a comparator function and the following custom properties:

  1. a custom sort order for the possible values in the ‘status’ field
  2. which field should be used for sorting
  3. which direction to sort

The Collection and Model classes I’ve got so far:

The Collection

var ApplicationCollection = Backbone.Collection.extend({
  model: ApplicationModel,
  url: 'rest/applications',

  // sorting
  statusOrder: ['new', 'to_pay', 'payed', 'ready'],
  sortField: 'submission_timestamp',
  sortOrder: 'asc',
  sortBy: function() {
    console.log('ApplicationCollection.sortBy', this, arguments);
    console.log('this.comparator', this.comparator);
    var models = _.sortBy(this.models, this.comparator);
    if (this.sortOrder != 'asc') {
      models.reverse();
    }
    return models;
  },
  comparator: function(application) {
    console.log('ApplicationCollection.comparator', this, arguments);
    switch(this.sortField) {
      case 'status':
        return _.indexOf(this.statusOrder, application.get(this.sortField));
        break;
      case 'submission_timestamp':
      default:
        return application.get(this.sortField)
        break;
    }
  }
});

The Model

var ApplicationModel = Backbone.Model.extend({
  defaults: {
    'drupal_id': 0,
    'language': '',
    'last_name': '',
    'first_name': '',
    'address': '',
    'zip_code': '',
    'city': '',
    'country': '',
    'telephone': '',
    'cell_phone': '',
    'email': '',
    'date_of_birth': '',
    'email': '',
    'date_of_birth': '',
    'pilot_training_institute': '',
    'date_of_exam': '',
    'flight_hours_total': '',
    'date_of_last_flight': '',
    'date_of_mcc_certificate': '',
    'date_of_ir_renewel': '',
    'package': '',
    'submission_timestamp': '',
    'status': 'new'
  },
  urlRoot: 'rest/applications'
});

The current (undesired) result

I’ve got an instance of the collection stored in ‘pendingApplications’ like so:

var pendingApplications = new ApplicationCollection();
pendingApplications.fetch();

This loads applications from the server, and all works as planned. I can render a view with a list of applications, all properties are there on the models, etc.

To sort the collection I do the following:

pendingApplications.sortOrder = 'asc';
pendingApplications.sortField = 'current_timestamp'; // format: YYYY-mm-dd HH:mm:ss
pendingApplications.sort();

This triggers the sort function on the Collection. The console tells me the ‘ApplicationCollection.sortBy’ method executes within the scope of the ‘pendingApplications’ instance, which is as expected.

However, the ‘ApplicationCollection.comparator’ method executes within the global scope and I’m not sure why. Also none of the arguments on the comparator method contain the ‘pendingApplications’ instance.

What I would like is for my comparator method to be executed within the scope of the ‘pendingApplications’ instance instead, or at least I’d like to be able to somehow be able to access properties on the ‘pendingApplications’ instance.

Scope issue? Wrong approach? Any suggestions are welcome…

Does anyone know how I can resolve this issue? Or am I going about this the wrong way and is there another solution to arbitrarily defining custom sorts on a Backbone.Collection?

The Solution

I ended up implementing a sorting functionality as decorator for the Backbone.Collection.
The reason to do it this way is because I’ve also got a decorator for filtering items in a collection.
By using a sorting decorator I can apply sorting to the filtered sub-set of items which is potentially faster.

/**
 * returns a new Backbone.Collection which represents a sorted version of the
 * data contained within the original Backbone.Collection.
 *
 * @param {Backbone.Collection} original
 */
SortedCollection: function(original, criteria) {
  var sorted = new original.constructor(),

  // sensible defaults
  defaultSortCriteria = {
    custom: {},
    field: 'id',
    direction: 'asc'
  };

  // configuration
  sorted.sortCriteria = _.extend(defaultSortCriteria, criteria);

  // do the stuff
  sorted.comparator = function(a, b) {
    // @formatter:off
    var criteria = this.sortCriteria,
        custom, 
        field = criteria.field,
        direction = criteria.direction,
        valA,
        valB;
        // @formatter:on

    // custom sort
    if (_.has(criteria.custom, field)) {
      custom = criteria.custom[field];

      // custom param is a comparator itself.
      if (_.isFunction(custom)) {
        return custom(a, b);
      }
      // custom param is an example of a sorted array.
      else if (_.isArray(custom)) {
        valA = _.indexOf(custom, a.get(field));
        valB = _.indexOf(custom, b.get(field));
      }
      else {
        throw new Error('Invalid custom sorting criterium.');
      }
    }
    // nothing custom here, use the field value directly.
    else {
      valA = a.get(field);
      valB = b.get(field);
    }

    // compare that shizzle!
    if (valA > valB) {
      return (direction == 'desc') ? -1 : 1;
    }
    if (valA < valB) {
      return (direction == 'desc') ? 1 : -1;
    }
    else {
      if (a.get('id') > b.get('id')) {
        return (direction == 'desc') ? -1 : 1;
      }
      else if (a.get('id') < b.get('id')) {
        return (direction == 'desc') ? 1 : -1;
      }
      else {
        return 0;
      }
    }
  };

  // update collection if original changes
  original.on("add", function(model) {
    sorted.add(model);
  });
  original.on("reset", function() {
    sorted.reset(original.models);
  });
  original.on("remove", function(model) {
    sorted.remove(model);
  });

  return sorted;
}

Usage of the decorator:

original = new ApplicationsCollection();
sortable = SortedCollection(original);
sortable.sortCriteria = { 
  sortField: 'submission_timestamp',
  sortDirection: 'desc'
}
sortable.sort();

The above snippet does the following:

  • Instantiates a new ApplicationsCollection;
  • Instantiates a Sortable Collection that extends the original and listens to relevant events on the original collection.
  • Tells the Sortable Collection to sort by ‘submission_timestamp’ property in descending order.
  • sorts the Sortable Collection.

The new Sortable Collection also stays sorted automatically when new models are added to or removed from the original Collection, or when the original Collection is reset.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-09T03:50:09+00:00Added an answer on June 9, 2026 at 3:50 am

    The comparator() function is called in the scope of the collection by default, at least in the most current version of Backbone.

    I suspect that you may have broken that by defining the sortBy() function. That function is already defined by Backbone, and is used internally by Backbone’s sort() function in some cases. Try removing that function and see if it works as expected.

    It appears that you’re just using sortBy() to reverse the order of your sort. That can be accomplished in the comparator() function by multiplying your return value by -1 when appropriate.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have an application with the desired functionality. Howerver, at certain times toasts are
Desired Outcome I want to have Vertical List with custom items on the left/right
I want to show only desired number of elements in list when I click
My application uses lseek() to seek the desired position to write data. The file
Scenario: Image with several areas mapped. A list of text on the page Desired
All applicants to our company must pass a simple quiz using C as part
I am using PyQt and want to create a menu based on a list
The desired functionality of the 'enhanced' combo box is a quick find method. Each
I have a JTable with row selection enabled. Before today, my desired functionality was
I'm having a bit of trouble getting the desired functionality from my function... Basically,

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.