Brandon
Brandon

Reputation: 2125

Reorder Backbone collection in initialize

I'm trying to find a way to reorganize a Backbone collection in the initialize function of a view. In my collection I have models that have attributes like:

id: ...,
name: ...,
sort: 2,
parent: 45

The parent property is what I am interested in. I would like to move all models that have a parent id of 45 to the beginning of a collection. There may be 200 models and maybe 30 have a parent of 45, 15 have a parent of 50, etc... I would like to the keep the chunk that I move in the same order it was in before (it's ordered by the sort property to begin with, I would like to keep it in that original order).

Any ideas?

Upvotes: 2

Views: 1010

Answers (2)

ggozad
ggozad

Reputation: 13105

Use underscore's groupBy

var mySorted = _.groupBy(collection.models, function (model) {
  return model.get('parent') === 45 ? 'top' : 'rest' ;
});

Then mysorted.top contains all the ones with parent 45. mySorted.rest obviously contains the rest ;)

Upvotes: 4

tkone
tkone

Reputation: 22728

Define a new comparator on your class. This will keep your collection in any order you wish.

Upvotes: 0

Related Questions