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')
});
当我运行代码时,我得到section.renderView()
不是函数的错误。需要帮助。如何迭代我的集合中的模型?
答案 0 :(得分:3)
您的第一个问题是您正在定义集合并错误地将其实例化。
model
声明需要在集合的定义中发生,而不是在实例化中发生:
PaperSectionsList = Backbone.Collection.extend({
model: PaperSection,
然后你只是实例化它:
var paper_sections = new PaperSectionsList();
这将使您的代码正常工作。
但是,我觉得有必要指出你对编码问题有些困惑。 Models
和Collections
永远不应该有名为render*
的函数。这些是View
问题。在您的情况下,处理它的惯用方法是必须查看:PaperSectionListView
(ul
)和PaperSectionListItem
(li
)。模板和渲染功能存在于这些视图中。
答案 1 :(得分:0)
我的代码工作如下......
但我认为上面的答案处理核心问题,我同意模型和集合不应该处理渲染逻辑的建议。
注意:我清理了一些JSLint错误,例如额外的逗号和丢失的分号。
var PaperSection = Backbone.Model.extend({
defaults: {
title: '',
position: ''
},
initialize: function () {
},
renderView: function () {
return "<li>" + this.get('title') + ", Position: " + this.get('position') + "</li>";
}
});
var PaperSectionsList = Backbone.Collection.extend({
url: '/admin/paper/section/list.html',
model: PaperSection,
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;
}
});
var 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);
}
});
$(function () {
var paper_sections = new PaperSectionsList({
model: PaperSection
});
var section_view = new PaperSectionView({
collection: paper_sections,
el: $('#paper_sections')
});
});