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?
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With