Backbone JS - this.model.models instead of this.collection?

I am new to Backbone JS and have been following the Christopher Coenraets wine cellar tutorial .

Everything works fine and dandy, but I don’t understand how it uses this.model.models to access the collection, not this.collection . In addition, when I try to change the code to the latter, it turns out that this.collection is undefined.

 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; } }); 
+4
source share
1 answer

Two things lead to your horror:

  • You can enter a collection in the form, but you want. The usual way is to pass the collection attribute, but here it is passed as a model in the router:

     this.wineList = new WineCollection(); this.wineListView = new WineListView({model:this.wineList}); 
  • collection.models contains a raw array of models in the collection

    collection.models models
    Raw access to the JavaScript array in the collection. Usually you want to use the get, at, or Underscore methods to access model objects, but sometimes a direct reference to the array is desirable.

If you want to use this.collection in your view, you must change the router to

 this.wineList = new WineCollection(); this.wineListView = new WineListView({collection: this.wineList}); 

and you can use it as

 window.WineListView = Backbone.View.extend({ tagName: 'ul', initialize: function () { this.collection.bind("reset", this.render, this); }, render: function (eventName) { // Backbone proxies Underscore methods on collections // _.each(this.collection.models, function (wine) { this.collection.each(function (wine) { $(this.el).append(new WineListItemView({model: wine}).render().el); }, this); return this; } }); 
+6
source

All Articles