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});这给了我Uncaught TypeError: Cannot read property 'models' of undefined,并且没有在页面上显示任何内容。
发布于 2014-02-24 08:38:29
这个this.model.models应该是this.collection
在视图中的呈现方法中,应该使用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
以下是您的提取调用可能无法工作的一些原因。首先检查您是否在使用web服务器,因为ajax请求可能由于安全原因使用文件系统而被阻止。我知道这是阻止在Chrome,除非你改变一个特定的设置。不确定火狐。
第二个原因是获取call是异步的。这意味着在运行initialize时很可能不会加载数据。
这意味着您需要进行以下调整。首先,您需要将侦听器添加到集合的add事件中,以便在任何时候添加项时,都会通知您的视图。
initialize: function() {
_.bindAll(this);
this.render();
// Listen to the `add` event in your collection
this.listenTo(this.collection,"add", this.renderText);
},接下来,我们需要向视图中添加一个函数,该函数将呈现单个项。
renderText: function(Text) {
var TextTemplate = this.template(Text.toJSON());
this.$el.append(TextTemplate);
}还可以回答关于每个循环中的this用户的其他问题。每个函数中的最后一个参数是要在执行的回调函数内部使用的作用域。因此,如果使用this作为第二个参数,它允许您使用this访问您的查看。
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);
});https://stackoverflow.com/questions/21982586
复制相似问题