javascriptbackbone.jsbackbone-viewsbackbone.js-collections

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


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!


Solution

  • 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}.