Search code examples
javascriptbackbone.js

Add model a the begin of a Backbone collection when using create


Is there a way to use create and at the new model at the beginn of the collection instead of appending it at the end?


Solution

  • Backbone delegates the insertion to Collection.add which means you can pass an at option to specify the position:

    var C = Backbone.Collection.extend({
        url: '/echo/json/'
    })
    var c= new C([
        {name: 1},
        {name: 2},
        {name: 3}
    ]);
    
    c.create({name: 4}, {at: 0});
    console.log(c.pluck('name'));
    

    will yield [4,1,2,3]

    And a Fiddle http://jsfiddle.net/nikoshr/p6fNR/