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!

Wednesday, September 25, 2013

Facebook Post vs Status objects

I spent several hours wrestling with this, so hopefully this will help someone else:

Facebook posts and statuses are remarkably similar. The differences are as follows:
  • Facebook posts are any posts a user makes anywhere
  • Facebook statuses are posts a user makes on his or her own wall/stream
As you may notice, all statuses are also posts. However, the Facebook Graph API treats these objects differently. For one, statuses have far fewer fields. They don't even have a field for something as simple as the privacy_level. Posts are far more interesting/descriptive.

In order to request a post object instead of a status object for a "status" (since all statuses are posts) prepend the user_id of the person who made the status to the id of the post.

So for example querying the Graph API for the object with id "100006765630328_1380118238890351" will return a POST object, whereas "1380118238890351"will return a STATUS object.