0

I am fairly new with Marionette.js and seem to be having some trouble rendering a Collection View.

I am receiving the following console error message when trying to show the view: Uncaught TypeError: Cannot read property 'toJSON' of undefined.

It seems that the collection is not binding to the child view. The instance of the Collection View looks OK, meaning I see the childView property and the collection property with the fetched models. The docs seem pretty straightforward on how to construct a collection view so not sure what I'm missing. Thanks.

Child view:
var UserProfile = Marionette.ItemView.extend({
  template: '',
  initialize: function() {
    this.template = Marionette.TemplateCache.get("#userprofile");
  },
  render: function() {
    console.log(this.collection); //undefined
    var data = this.collection.toJSON(); //error message here
    this.$el.html(this.template({data:data}));
  } 
});

//Collection view:
var UserView = Marionette.CollectionView.extend({  
  childView: UserProfile
});

// Fetch collection and show:
var myQuery = new Parse.Query(app.Models.User);
myQuery.limit(200).containedIn(option, uiArray);

var Contacts = Parse.Collection.extend({
  model: app.models.User,
  query: myQuery
});

var contacts = new Contacts();
contacts.fetch().then(function(contacts) {
  var userview = new UserView({collection:contacts});
  app.regions.get("content").show(userview);
})
joews
  • 29,767
  • 10
  • 79
  • 91
user2232681
  • 839
  • 4
  • 16
  • 33

1 Answers1

2

You are asking a "collection" in an ItemView. ItemView operates with an item. So it make sense to write something like this:

render: function() {
    console.log(this.model); //undefined
    var data = this.model.toJSON(); //error message here
    this.$el.html(this.template({data:data}));
    }   
});
kharandziuk
  • 12,020
  • 17
  • 63
  • 121
  • That seems to work. I guess that will allow me to use the ItemView when I just want to render a single model at some other place in the app? – user2232681 Nov 10 '15 at 23:10