Javascript Backbone.js怀疑
我有以下父对象:Javascript Backbone.js怀疑,javascript,backbone.js,Javascript,Backbone.js,我有以下父对象: Context = { ContextModel: Backbone.Model.extend({ //model Code }), ContextList:Backbone.Collection.extend({ model : Context.ContextModel // collection Code }), Contexts: new Context.ContextList, ContextVie
Context = {
ContextModel: Backbone.Model.extend({
//model Code
}),
ContextList:Backbone.Collection.extend({
model : Context.ContextModel
// collection Code
}),
Contexts: new Context.ContextList,
ContextView: Backbone.View.extend({
// view Code
})
}
在上面的代码中,model:Context.ContextModel抛出一个错误,表示uncaughtreferenceerror:Context未定义。我已经定义了上下文对象,但不知为什么它没有看到它。谁能帮我一下吗。
谢谢让我们看看JavaScript解释器的眼睛。您有一个语句,Context={…}。为了执行该语句,它必须首先构造{…},以便将其分配给上下文。为了构造{…},它需要计算新的Context.ContextList。不幸的是,它仍然在构造{…}部分,还没有为上下文分配任何内容。因此,当您尝试创建Context.ContextList的新实例时,上下文是未定义的。在创建Context.ContextList时,尝试访问Context.ContextModel时遇到相同的问题。试试这个:
Context = {
ContextModel: Backbone.Model.extend({
//model Code
}),
ContextView: Backbone.View.extend({
// view Code
})
}
Context.ContextList=Backbone.Collection.extend({
model : Context.ContextModel
// collection Code
});
Context.Contexts=new Context.ContextList();
问题解决了
问题在于,您在分配对象文本时的执行逻辑。上下文变量仅在赋值完成后才存在,而赋值是在构造对象文本后完成的
为了避免这种情况,不要在对象文本中执行逻辑,它应该是值和方法的静态集合。我更喜欢这样写
var ContextModel = Backbone.Model.extend({
//model Code
})
var ContextList = ContextModel({
model : contextModel
// collection Code
})
var Context = {
ContextModel: ContextModel,
ContextList: ContextList,
Contexts: new ContextList,
ContextView: Backbone.View.extend({
// view Code
})
}
var ContextModel = Backbone.Model.extend({
//model Code
})
var ContextList = ContextModel({
model : contextModel
// collection Code
})
var Context = {
ContextModel: ContextModel,
ContextList: ContextList,
Contexts: new ContextList,
ContextView: Backbone.View.extend({
// view Code
})
}