PaperSection = Backbone.Model.extend({
defaults: {
title: '',
position: ''
},
initialize: function(){
},
renderView: function(){
return "<li>"+this.get('title')+", Position: "+this.get('position')+"</li>"
}
});
PaperSectionsList = Backbone.Collection.extend({
url: '/admin/paper/section/list.html',
size: 6,
initialize: function(){
this.add(new PaperSection({
id:1,
title: "Hello World",
position:1
}));
},
comparator: function(section){
return section.get('position');
},
renderView: function(){
var html = "<ul>";
_.each(this.models, function(section){
html += section.renderView();
});
if(_.size(this.models) < this.size){
html+="<li><a href='#add_section' class='btn btn-success btn-small' id='add_section'>Add Section</a></li>"
}
html+="</ul>";
return html;
}
});
PaperSectionView = Backbone.View.extend({
initialize: function(){
this.render();
},
render: function(){
console.log(this.collection.get(1));
var html = this.collection.renderView();
this.$el.html(html);
}
});
var paper_sections = new PaperSectionsList({
model: PaperSection,
});
var section_view = new PaperSectionView({
collection: paper_sections,
el: $('#paper_sections')
});
When I run the code I get the error that section.renderView() is not a function. Need help with this. How do I iterate over models in my collection?
Your first problem is that you are defining your collection and instantiating it incorrectly.
The
modeldeclaration needs to happen in the collection’s definition, not in the instantiation:And then you just instantiate it:
That will get your code working.
But, I feel compelled to point out that you have some confusion about your coding concerns.
ModelsandCollectionsshould never have functions calledrender*. These areViewconcerns. In your case, the idiomatic way of handling it would be to have to views:PaperSectionListView(ul) andPaperSectionListItem(li). The templates and render functions live in those views.