var Text = Backbone.Model.extend({});
Texts = Backbone.Collection.extend({
model: Text,
url: '/data.json',
});
var TextsView = Backbone.View.extend({
initialize: function() {
_.bindAll(this);
this.render();
},
el: "#Texts",
template: _.template($('#TextTemplate').html()),
render: function(e){
_.each(this.model.models, function(Text){
var TextTemplate = this.template(Text.toJSON());
$(this.el).append(TextTemplate);
}, this);
return this;
}
})
var Texts = new Texts();
Texts.fetch();
var TextView = new TextsView({collection: Texts});
这给了我未捕获的类型错误:无法读取未定义的属性“模型”
并且不在页面上显示任何内容。
最佳答案
这个this.model.models
应该是this.collection
在 View 中的渲染方法中,您应该使用 this.collection.each
而不是 _.each
函数。
render: function(e){
this.collection.each(function(Text){
var TextTemplate = this.template(Text.toJSON());
$(this.el).append(TextTemplate);
}, this);
return this;
}
如果您想使用_.each
函数,那么您将需要直接访问集合中的模型数组,如@dfsq指出的那样。这可以通过使用 this.collection.models 来完成。
render: function(e){
_.each(this.collection.models, function(Text){
var TextTemplate = this.template(Text.toJSON());
$(this.el).append(TextTemplate);
}, this);
return this;
}
编辑2
以下是您的 fetch 调用可能无法正常工作的一些原因。首先检查您是否正在使用 Web 服务器,因为出于安全原因,使用文件系统可能会阻止 ajax 请求。我知道这在 Chrome 中被阻止,除非您更改某个设置。不确定 Firefox。
第二个原因是获取调用
是异步的。这意味着当您运行 initialize
这意味着您需要进行以下调整。首先,您需要向集合的添加事件添加一个监听器,以便每当添加项目时,您的 View 都会收到通知。
initialize: function() {
_.bindAll(this);
this.render();
// Listen to the `add` event in your collection
this.listenTo(this.collection,"add", this.renderText);
},
接下来我们需要向您的 View 添加一个函数来渲染单个项目
renderText: function(Text) {
var TextTemplate = this.template(Text.toJSON());
this.$el.append(TextTemplate);
}
还可以回答有关每个循环中 this
用户的其他问题。每个函数中的最后一个参数是您要在执行的回调函数内部使用的范围。因此,如果您使用 this
作为第二个参数,它允许您使用 this
访问您的 View 。
this.collection.each(function(Text){
var TextTemplate = this.template(Text.toJSON());
$(this.el).append(TextTemplate);
}, this);
如果您不添加this
,那么您需要执行以下操作:
var view = this;
this.collection.each(function(Text){
var TextTemplate = view.template(Text.toJSON());
$(view.el).append(TextTemplate);
});
关于javascript - 主干 : render this collection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21982586/