Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the index of an item added to a Backbone collection via fetch?

I’ve got a Backbone Collection. I’m using fetch({add:true}) to fetch new items from my server, and add them to the collection.

I’ve bound a listener function to the collection’s add event. I’d like that function to get the index at which the item was added to the collection.

Backbone’s documentation for Collection.add says “if you're a callback listening to a collection's "add" event, options.index will tell you the index at which the model is being added to the collection.”

I’ve logged the arguments that seem to be passed to my listener function to the console and had a look at them. As far as I can tell, the first argument is the item added, followed by a temporary collection object created to hold it when it came back from the server. I don’t seem to have an object with an index property.

How can I get the index at which the item was added to the collection?

like image 438
Paul D. Waite Avatar asked Feb 07 '12 13:02

Paul D. Waite


People also ask

What is collections in Backbone JS?

A Backbone. js Collections are a group of related models. It is useful when the model is loading to the server or saving to the server. Collections also provide a helper function for performing computation against a list of models.

Does backbone require jQuery?

You can use the Backbone. Model without jQuery, but Backbone. View will require either jQuery or Zepto, just like the docs state. Chances of not using view and router is low enough.

How does Backbone JS work?

BackboneJS provides various building blocks such as models, views, events, routers and collections for assembling the client side web applications. When a model changes, it automatically updates the HTML of your application. BackboneJS is a simple library that helps in separating business and user interface logic.


2 Answers

To anybody reading this in the future, NOTE: since version 0.9.9, options.index is no longer set. From the changelog:

To improve the performance of add, options.index will no longer be set in the add event callback. collection.indexOf(model) can be used to retrieve the index of a model as necessary.

like image 105
rkofman Avatar answered Sep 22 '22 14:09

rkofman


Check the third argument to your bind function, it should contain the index property

var c=new Backbone.Collection();
c.bind("add",function(model,collection,opts){
    console.log(opts);
});

c.add({});
c.add({});

Edit : I just checked Backbone 0.5.3 and it would seem options.index is only available in version 0.9

like image 32
nikoshr Avatar answered Sep 21 '22 14:09

nikoshr