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]);
},
The Backbone. js collection models specify the array or models which are created inside of a collection. Syntax: collection.
Advertisements. Collections are ordered sets of Models. We just need to extend the backbone's collection class to create our own collection. Any event that is triggered on a model in a collection will also be triggered on the collection directly.
Backbone. Backbone has been around for a long time, but it's still under steady and regular development. It's a good choice if you want a flexible JavaScript framework with a simple model for representing data and getting it into views.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With