Reputation: 2125
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
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
Reputation: 22728
Define a new comparator on your class. This will keep your collection in any order you wish.
Upvotes: 0