Best Practice for moving backbone model within a collection
backbone.js, backbone.js-collections, javascript
Solution
I wrote this solution for my most recent project. It seems to be a similar interface to what you described - a sortable list. This method is bound to the collection.
reorder: function(new_index, original_index) {
// If nothing is being changed, don't bother
if (new_index === original_index) return this;
// Get the model being moved
var temp = collection.at(original_index);
// Remove it
collection.remove(temp);
// Add it back in at the new index
collection.add(temp, { at: new_index });
return this;
}
Most of my own code has been removed, but that is the core functionality. Backbone's `at` option makes this really easy.
Problem
Related Questions - BackboneJS best way to rearrange models in a collection while maintaining 0-indexed ordinal property for each model How can I move a model within a collection? I have a Backbone collection, visually represented in a list. This list is drag/droppable. Any item can be moved to an arbitrary position in the collection (ie - not a sort). I've seen some examples that use the collection's native remove/add to put the model in the right place. However, Backbone internally calls set when models are added, which then calls a bunch of methods related to events and sorts it at the end. Is there any downside to just splicing the model to the correct position? Remove/Add: See examples in first linked question. Splice: Second example Function I'm currently using: ``` moveTo: function(oldIndex, newIndex){ oldIndex = oldIndex instanceof Backbone.Model ? this.at(oldIndex) : oldIndex; var spliced = this.models.splice(oldIndex, 1); this.models.splice(newIndex, 0, spliced[0]); this.trigger("move",[oldIndex,newIndex]); }, ```