Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I insert a model into a backbone.js collection in a specific index?

I need to insert a model into a Collection at position Collection.length-2. The last model in the collection should always stay the last model in the collection.

What I tried so far:

I added one "page" model to the Collection "Pages" and then tried to swap them around by changing their sequence:

var insertedpage = Pages.at(Pages.length-1);
var lastpage = Pages.at(Pages.length-2);
insertedpage.set({sequence: Pages.length-1});
lastpage.set({sequence: Pages.length});

I also tried to remove the last page, then add a new page and then add the last page back in.

var lastpage =  Pages.pop();
Pages.add({example1: example2});
Pages.push(lastpage);

neither of these worked. The newly added page still appears as last model in the Collection. Do I need to call some kind of order function after this?

like image 486
Dine Avatar asked Apr 17 '12 16:04

Dine


People also ask

How do you create a model in Backbone JS?

Model class while creating your own backbone Model. When a model instance is created, the class's constructor gets called and it is invoked by defining the initialize function when the model is created. It gets the value of an attribute on the model. It sets the value of an attribute in the model.

How can we get the attribute value of a model in Backbone JS?

js Get model is used to get the value of an attribute on a model. Syntax: model. get(attribute)


2 Answers

Backbone.Collection.add() takes an options object that supports an at key for specifying the index.

Pass {at: index} to splice the model into the collection at the specified index.

Example:

Pages.add({ foo: bar }, { at: Pages.length - 2 })
like image 157
Rob Hruska Avatar answered Oct 05 '22 10:10

Rob Hruska


Along the same suggestion as Rob Hruska, use Backbone.Collection.add() with at in the options object.

Pages = new Backbone.Collection([
  {id:1, foo:'bar'},
  {id:2, foo:'barista'}  /* Last model should remain last */
]);

/* Insert new "page" not at the end (default) but length minus 1 */
Pages.add({id:3, foo:'bartender'}, { at: Pages.length - 1 });

Pages.at(0).id === 1; // true
Pages.at(Pages.length - 2).id === 3; // true
Pages.at(Pages.length - 1).id === 2; // true

You mentioned that Pages seems to be sorted by the attribute sequence; do you happen to have a comparator function defined on the Pages collection?

Another question, did you want to update this attribute sequence on ALL existing page models currently in the collection when a new page is added to the 2nd to the last position? Or was that attribute an attempt to accomplish your original question?

like image 21
Kaleb F. Avatar answered Oct 05 '22 10:10

Kaleb F.