Search code examples
javascriptbackbone.js

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.


Solution

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

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