I am trying to sort my collection when I add a new object to it, but it is not sorting and there are no errors

55 Views Asked by At

in my Backbone view, a user can add a new educational research opportunity by hitting a button.

Each research opportunity has a sequence in the database and this is how it's ordered on my page.

When I add it, it writes to the database fine and the sequence is correct, but it doesn't sort it until after I hit refresh/reload page in the browser.

I am asking it to sort but it still doesn't work.

Here is the function in my view:

addResearchOpp: function () {
    var self = this;
    this.educationalOpp.research().then((r) => {
        self.model.collection.add(r);
        self.collection.sort({ silent: true });
    });
},

Is there anything else I need to do ?

thanks!

2

There are 2 best solutions below

0
Nicolas Zozol On BEST ANSWER

You don't need self here, and this.model.collection is weird. It looks like you are not sorting what you are adding. I would suggest just.

this.collection.add(r)

Also the {silent:true} explains why you need to refresh. Except if you have a very strong reason, like batching and improving performances, I would not use {silent:true}.

0
Julian On

In addition to what Nicolas Zozol wrote, you may need to set the comparator of your collection. If sequence is the actual name of the field by which the models are ordered, it would look like this:

var ResearchOpportunities = Backbone.Collection.extend({
    // ...
    comparator: 'sequence',
    // ...
});