1

I would like to ask You how to add item to collection but beetween other items. For example. I have a todoItem { name: todoItem2, date: 2012-11-24}, and I want to add it beetween other items in collection (beetween todoItem1 and todoItem3 not after todoItem3).

Now I add items looks like:

items.push(form_Data); this.collection.add(new itemM(form_Data));

Is any simple way to do that?

Agata
  • 554
  • 1
  • 9
  • 18
  • Possible duplicate of [How do I insert a model into a backbone.js collection in a specific index?](http://stackoverflow.com/questions/10195102/how-do-i-insert-a-model-into-a-backbone-js-collection-in-a-specific-index) – T J Jan 08 '16 at 09:57

2 Answers2

9

If you know the index in the collection, you can pass it as an option. For example:

this.collection.add(new Item(data), {at: 3});

If you know the order that you want the collection to be in, you can implement sort or sortBy on the collection. Then any model instance you add will be placed in the correct position automatically.

I recommend you read the docs at http://backbonejs.org.

mu is too short
  • 426,620
  • 70
  • 833
  • 800
erturne
  • 1,799
  • 1
  • 15
  • 29
1

If items.collection is an ordinary JavaScript array, this article may help you How to insert an item into an array at a specific index?

Community
  • 1
  • 1
Jim Blackler
  • 22,946
  • 12
  • 85
  • 101