Search code examples
collectionsbackbone.js

How do you swap element position in a collection in backbone.js


I am using backbone.js. The elements in my collection are just in the order that they are added. However, I want the ability to switch the position of elements. How do you do this?


Solution

  • You could do something like this:

    var MyCollection = Backbone.Collection.extend({
        swapItems : function(index1, index2) {
            this.models[index1] = this.models.splice(index2, 1, this.models[index1])[0];
        }
    });
    

    This accesses the models array directly then will swap the items specified by the indices.