开发者

Backbone.js Doubt

开发者 https://www.devze.com 2023-03-20 00:13 出处:网络
I have the following Parent Object: Context = { ContextModel: Backbone.Model.extend({ //model Code }), ContextList:Backbone.Collection.extend({

I have the following Parent Object:

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
   }) 
}

In the above code,model : Context.ContextModel throws an error saying Uncaught ReferenceError: Context is not defined. I have defined the Context Object b开发者_StackOverflow社区ut somehow it does not see it. Could someone please help me out. Thanks


Let's look through the eyes of the JavaScript interpreter. You have a statement, Context = { ... }. In order to execute that statement, it has to first construct the { ... } so it can assign it to Context. In order to construct the { ... }, it needs to evaluate new Context.ContextList. Unfortunately, it's still constructing the { ... } part, and has not assigned anything to Context yet. Thus, Context is undefined when you attempt to create a new instance of Context.ContextList. You have the same problem trying to access Context.ContextModel when creating Context.ContextList. Try this:

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 Context = {};
Context.ContextModel = Backbone.Model.extend({
      //model Code
});
Context.ContextList = Backbone.Collection.extend({
   model : Context.ContextModel
   // collection Code
});
Context.Contexts = new Context.ContextList;
Context.ContextView = Backbone.View.extend({
   // view Code
}); 

Problem solved.

The issue is that your doing logic in your assignment of the Object literal. The Context variable only exists after the assignment is finished, which is finished after the object literal is constructed.

To avoid this don't do logical execution in a object literal, it should be a static collection of values and methods.


I prefer writing it this way

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
   }) 
}
0

精彩评论

暂无评论...
验证码 换一张
取 消