Javascript 骨干新手:如何从收藏中获得第一个模型?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8571083/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Backbone Newbie: How to get first model from collection?
提问by PlankTon
I have a collection which returns a model for each date within a given range (fed in through a Rails controller).
我有一个集合,它为给定范围内的每个日期返回一个模型(通过 Rails 控制器输入)。
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.
或者,我可以通过从 rails 调用 router() 来传递所需的值,但这看起来有点难看。
Finally, I could do up an entirely new collection justto 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.
关于我应该如何去做的任何建议?假设将模型数据反馈到集合中并不是什么禁忌,我想我在问如何做到这一点。
回答by djlumley
Backbone.js
collections have access to Underscore.js
methods.
Backbone.js
集合可以访问Underscore.js
方法。
MyCollection.first()
should return the first model from a collection.
MyCollection.first()
应该从集合中返回第一个模型。
回答by Ivan Castellanos
collection.at(0) //etc
But if you have to check if there is at least one element
但是如果你必须检查是否至少有一个元素
if(collection.length){
collection.at(0) //etc
}