How to transfer a model to a collection?

Let's say I have a simple 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 in a collection? 5th - to 2nd position? Thus, sorting by model field is not performed, but the manual sorting order is simply changed.

Note. I simplified the Book1, ... models. They are, of course, Backbone.Model s.

+2
collections model
source share
1 answer

You can directly access an array of models to reorder. Essentially based on this question, Move an array element from one position of the array 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 the demo http://jsfiddle.net/nikoshr/5DGJs/

+5
source share

All Articles