Thursday, November 21, 2013

Adding models to backbone collection without sorting

We've been using backbone.js at work a lot lately and I'm loving it so far. I wanted to share one thing I ran across recently where the solution to my problem was non-obvious.

Problem: I needed to sort a backbone collection using a natural sort algorithm. In order to sort the collection, you need to set a comparator - as in:

Collection = Backbone.Collection.extend({
    comparator : function () { // ... comparator logic }
});

However, the problem with this is that every time you do an insert, the collection resorts itself - which sucks when you're trying to add 4000 items to the list from the server like I was! In order to get around this, when you're adding something to the collection, you need to pass in the parameter sort = false, like so:

var collection = new Collection;
collection.add([model1, model2 ... modelN], { sort : false });
collection.sort()

Ta da! Now your backbone collection won't be sorted when you're adding those items to it.

I hope that helps people!