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!

Related Posts:

  • Discovering AngularJS I've recently been pointed towards AngularJS by a mentor. At work, we typically use BackboneJS for our client-side framework needs. Since Backbone is so minimalist, over the past few years we've learned some (sometimes expen… Read More
  • Learning Angular | Using a factory to make an API call I was recently building an Angular app in which I had a search page and a search results page. Obviously, the API call would be made after a user hit the search button on the search page, but the question was whether I shoul… Read More
  • 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… Read More
  • Postback not happening on ASP:LinkButton with Adblock Plus I recently had a problem while working on an ASP.NET website where I had a page doing a postback on an ASP LinkButton, except in FireFox with AdBlock enabled, the postback just wasn't happening. Clicking on the button result… Read More

0 comments:

Post a Comment