gpt4 book ai didi

javascript - 主干 : render this collection

转载 作者:行者123 更新时间:2023-11-29 22:04:02 25 4
gpt4 key购买 nike

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 并且不在页面上显示任何内容。

最佳答案

这个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

以下是您的提取调用可能无法正常工作的一些原因。首先检查您使用的是 Web 服务器,因为使用文件系统出于安全原因可能会阻止 ajax 请求。我知道这在 Chrome 中被阻止,除非你更改某个设置。不确定 Firefox。

第二个原因是fetch调用是异步的。这意味着当您运行 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com