2011-07-14 106 views
0

我有以下父對象:Backbone.js的懷疑

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拋出一個錯誤說Uncaught ReferenceError: Context is not defined。我已經定義了上下文對象,但不知何故它沒有看到它。有人能幫助我嗎? 謝謝

回答

5

讓我們來看看JavaScript解釋器的眼睛。你有一個聲明,Context = { ... }。爲了執行該聲明,它必須首先構建{ ... },以便它可以將其分配給Context。爲了構建{ ... },它需要評估new Context.ContextList。不幸的是,它仍在構建{ ... }部分,但尚未將任何內容分配給Context。因此,當您嘗試創建Context.ContextList的新實例時,Context未定義。嘗試在創建Context.ContextList時嘗試訪問時遇到同樣的問題。試試這個:

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(); 
2
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 
}); 

問題解決了。

問題是,你在對象文字賦值中做邏輯。 Context變量僅在賦值完成後才存在,該賦值在構造對象文字後完成。

爲了避免這種情況,不要在對象文字中執行邏輯執行,它應該是一個靜態的值和方法集合。

+0

感謝。這非常有幫助 – felix

0

我寧願寫這種方式

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