2

Say I'm having a plain Backbone.Collection with some models in it:

var Library = Backbone.Collection.extend({
    model: Book
});

lib = new Library(
   [Book1, Book2, Book3, Book4, Book5, Book6]
]);

How can I move a model within a collection - e.g. the 5th one to the 2nd position? So no sorting by a model field but just changing the sort order manually.

Note: I simplified the models Book1, .... They are of course Backbone.Models.

acme
  • 14,654
  • 7
  • 75
  • 109

1 Answers1

5

You can directly access the array of models to modify the order. Loosely based on this question Move an array element from one array position to another, something like this should work:

var c = new Backbone.Collection([{id: 1}, {id: 2}, {id: 3}, {id: 4}, {id: 5}]);
console.log(c.pluck("id"));

var from_ix = 4,
    to_ix = 1;
c.models.splice(to_ix, 0, c.models.splice(from_ix, 1)[0]);
console.log(c.pluck("id"));

And a demo http://jsfiddle.net/nikoshr/5DGJs/

Community
  • 1
  • 1
nikoshr
  • 32,926
  • 33
  • 91
  • 105
  • Thanks a lot! I completely forgot about the `collection.models` array and thought there must be some functionality within `Collection`. I missed the forest for the trees ;-) – acme Feb 17 '12 at 11:57