我有这个集合视图
define([
'jquery',
'underscore',
'backbone',
'views/project',
'collections/project-collection',
'templates'
], function ($, _, Backbone, ProjectView, ProjectCollection, JST) {
'use strict';
var ProjectListView = Backbone.View.extend({
template: JST['app/scripts/templates/projectList.ejs'],
el: $('#content'),
render: function() {
var projectCollection = new ProjectCollection();
projectCollection.fetch();
projectCollection.each(this.addOne(),this);
return this;
},
addOne: function(project) {
console.log('addOne function');
var projectView = new ProjectView({model: project});
this.$el.html( projectView.render().el);
}
});
return ProjectListView;
});
无论我尝试什么,模型永远不会传递给addOne函数,因此在此方法实例化的视图中调用
this.model.toJSON()
导致旧的'无法调用方法.toJSON of undefined'错误。当这个集合视图被实例化时,我尝试注入集合,但也没有工作。显然,这是在依赖数组中,并且也不起作用。该模型肯定存在,因为我可以将projectCollection.model记录到render函数内的控制台。我很难过。
答案 0 :(得分:0)
我发现你的render
存在两个问题:一个你知道,另一个你不知道。
第一个问题就在这里:
projectCollection.each(this.addOne(), this);
this.addOne()
上的括号在此处调用addOne
方法,而不是将this.addOne
函数作为回调传递给each
。你想要这个:
projectCollection.each(this.addOne, this);
第二个问题是你必须等待集合的fetch
返回,然后集合中才会有任何内容。您可以使用fetch
's回调:
var _this = this;
projectCollection.fetch({
success: function() {
projectCollection.each(_this.addOne, _this);
}
});
或者您可以使用fetch
将触发的各种事件,有关详细信息,请参阅fetch
文档。