Torben Pi Jensen
Torben Pi Jensen

Reputation: 870

BackboneJS: Sorting collection of linked items

I have some trouble figuring out how to sort a BackboneJS collection containing linked items. Is it at all possible to do efficiently? (I am thinking of making one returning the count of previous elements, but that is really inefficient)

What should the comparator be? - and is a double linked list required?

My items look like

[ { id: 1, name: 'name', previousItem: 2 }, { id: 2, name: 'othername', previousItem: null } ]

Upvotes: 0

Views: 100

Answers (2)

Gohn67
Gohn67

Reputation: 10648

Here is the basic code to build the collection. I'm assuming you are using a Backbone Model here. In the loop, you need to add your models to the front of the collection (unshift) since you only know the previous item.

The key here is knowing what the last item is though. If you don't know it, then this will not work.

model = frontItem;
while (model != null) {
   collection.unshift(model);
   model = model.attr('previousItem')    
}

Upvotes: 1

Rommel Castro
Rommel Castro

Reputation: 460

there is a discussion about this on github, you can also use comparator, if you want to use comparator you need underscore

var PhotoCollection = Backbone.Collection.extend({
    model: Photo,
    comparator: function(item) {
        return item.get('pid');
    }
});

Upvotes: 0

Related Questions