下面是我初始化时应该接收模块名称的视图的初始化函数,以便从集合中获取正确的数据。
问题是:
TypeError:e未定义
我用下面的代码犯了什么错误?
initialize: function() {
var that = this;
if(this.options.module === 'questions'){
require([
'app/collections/questions'
], function(QuestionsCollection){
var moduleCollection = new QuestionsCollection();
that.collection = moduleCollection;
moduleCollection.fetch({
reset: true,
success: function(){},
error: function(){}
});
});
}
this.listenTo(this.collection, 'reset', this.render);
this.listenTo(Backbone, 'close:Home', this.close);
},
答案 0 :(得分:4)
我认为这是一个范围问题,其中require模块处于闭包状态。请尝试以下方法:
initialize: function() {
var that = this;
if(this.options.module === 'questions'){
require([
'app/collections/questions'
], function(QuestionsCollection){
var moduleCollection = new QuestionsCollection();
moduleCollection.fetch({
reset: true,
success: function(){},
error: function(){}
});
that.listenTo(moduleCollection, 'reset', that.render);
});
}
this.listenTo(Backbone, 'close:Home', this.close);
},
答案 1 :(得分:1)
您的问题是riquire.js
,当您编写require([/*jsFile*/], callback);
时,callback
的调用是在jsFile
加载后异步进行的。因此,当您在此之后立即致电require([...
时,请致电this.listenTo(this.collection, 'reset', this.render);
,并且在执行此最后一行时,jsFile
尚未加载且callback
尚未调用this.collection
未定义。
查看此示例http://jsfiddle.net/ZZuGC/1/以及console.log('require');
&的顺序console.log('listenTo');
将打印到控制台。
我认为您的问题的解决方案如下:
initialize: function() {
var that = this;
if(this.options.module === 'questions'){
require([
'app/collections/questions'
], function(QuestionsCollection){
var moduleCollection = new QuestionsCollection();
that.collection = moduleCollection;
// here is my suggestion
that.listenTo(that.collection, 'reset', that.render);
moduleCollection.fetch({
reset: true,
success: function(){},
error: function(){}
});
});
}
this.listenTo(Backbone, 'close:Home', this.close);
},