The best way to sort a collection in a CompositeView

By : js999

I am trying to sort a collection in a Marionette.CompositeView.
I have a collection which looks like this:

   {id: 1, name: 'bar'},
   {id: 2, name: 'boo' },
   {id: 3, name: 'foo' }

I need to sort the collection by id in reverse order.
Actually it work only when I reload the page.
When I add a new model, the new item is added apparently random to the list.
If I refresh the page, they will be well sorted.

My questions are:
1) how to fix the problem when I add a new model?
2) it will be possible to improve the code?

Here is my code:

return Marionette.CompositeView.extend({

    initialize: function () {

    onRender: function () {
        var collection =  this.collection;

        collection.comparator = function (collection) {
            return - collection.get('id');

    onSuccess: function () {
        this.collection.sort(); // the messageModel seems to be added 
                                // apparently randomly to the list. 
                                // only if I refresh the page it will be ok
By : js999


Can you declare the .comparator when you create the collection? from your code the .comparator exists only on local variable var collection inside onRender function. If defined correctly the collection must be automatically sorted and you do not need to call .sort after adding new model

var Chapters = new Backbone.Collection({
    comparator = function(chapter) {
        return chapter.get("id");

This video can help you solving your question :)
By: admin