I’m reading a Backbone tutorial http://coenraets.org/blog/2011/12/backbone-js-wine-cellar-tutorial-part-1-getting-started/ on building a wine cellar application. The author of the tutorial doesn’t explain one point clearly and I can’t figure it out from the documentation. Namely, the use of this.model.models, which you see in the render function view below
window.WineListView = Backbone.View.extend({
tagName:'ul',
initialize:function () {
this.model.bind("reset", this.render, this);
},
render:function (eventName) {
_.each(this.model.models, function (wine) {
$(this.el).append(new WineListItemView({model:wine}).render().el);
}, this);
return this;
}
});
The model for this view is actually a collection
list:function () {
this.wineList = new WineCollection();
this.wineListView = new WineListView({model:this.wineList});
And the collection declares the Wine as its model
window.WineCollection = Backbone.Collection.extend({
model:Wine,
url:"../api/wines"
});
So, when WineListView is instantiated, it’s this.model is actually the Wine List Collection. And, from the documentation, models provides access to an array of models inside a collection
modelscollection.models
Raw access to the JavaScript array of models inside of the collection. Usually you'll want to use get, at, or the Underscore methods to access model objects, but occasionally a direct reference to the array is desired.
So if this.model is already the collection of wines (due to the collection being declared as the model in the view), why is it necessary to do this.model.models? to essentially get the collection again?
It looks like this is essentially a stylistic choice. The code
simply iterates through the models in the collection, and should be equivalent to:
I would have thought the second version was easier to read, but each to his/her own…