This is a really simple problem. I'm trying to print out each instance of the Student Model in the Collection. There's one line in the printData
function: this.$el.append(model_view.el);
where I think I'm missing something. Full JSFiddle example here.
// Model
var Student = Backbone.Model.extend({
defaults: {
name: '',
age: '',
major: '',
}
});
// Collection
ExampleCollection = Backbone.Collection.extend({
model: Student
});
// Model View
var ModelView = Backbone.View.extend({
el: $('.example-content'),
template: _.template( $('#example-target').html() ),
render: function(){
var studentTemplate = this.template(this.model.toJSON());
this.$el.html(studentTemplate);
}
});
// Collection View
var CollectionView = Backbone.View.extend({
render: function(){
this.collection.each(this.printData, this);
return this;
},
printData: function(target){
var model_view = new ModelView({ model: target });
this.$el.append(model_view.el);
}
});
var matt = new Student({name: 'Matt', age: 32, major: 'French'});
var nick = new Student({name: 'Nick', age: 27, major: 'Science'});
var ellen = new Student({name: 'Ellen', age: 63, major: 'Geriatrics'});
var studentList = new ExampleCollection([matt, nick, ellen]);
var collection_view = new CollectionView({ collection: studentList });
collection_view.render();
Well, your CollectionView
doesn't have an 'el' specified, so you shouldn't be trying to append anything to it. Your ModelView
s are putting themselves on the page, you don't need to do anything else to them.
Now then, you have a syntax error: Take off the .el
in that line you specified. In fact, the easiest way to fix that line is to simply call render()
on each of the Students in your collection and stop trying to append them to something.
I believe you are trying to show all of the items, not just one, so each of the items should be appending themselves to their parent element... Call .append(studentTemplate)
, not .html(studentTemplate)
.
See fiddle