How can I move a model within a collection?

2019-04-14 02:29发布

问题:

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.

回答1:

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/