Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone Newbie: How to get first model from collection?

I have a collection which returns a model for each date within a given range (fed in through a Rails controller).

In my view for the collection, I'd like to display the month for the first date from the collection...I'm just wondering what the most elegant way of achieving that is?

It seems the most straightforward would be to access the array of models via the collection, nab the first one, and run the required method within that model to retrieve the month name. Seems straightforward, but I can't figure out how to nab the first model from within the collection.

Alternatively, I could pass the required value in through the call to router() from rails, but that seems a little ugly.

Finally, I could do up an entirely new collection just to retrieve that one value, but again - seems excessive.

Any suggestions on how I should go about doing this? Assuming it's not too much of a taboo to feed model data back into a collection, I guess I'm asking how to do that.

like image 790
PlankTon Avatar asked Dec 20 '11 05:12

PlankTon


2 Answers

Backbone.js collections have access to Underscore.js methods.

MyCollection.first() should return the first model from a collection.

like image 199
djlumley Avatar answered Nov 18 '22 16:11

djlumley


collection.at(0) //etc

But if you have to check if there is at least one element

if(collection.length){
    collection.at(0) //etc
}
like image 8
Ivan Castellanos Avatar answered Nov 18 '22 14:11

Ivan Castellanos