2012-07-15 43 views
0

我有以下設置(僞咖啡代碼)。模型和集合使用Require.js加載。循環引用與Backbone.js和Require.js模型中的集合

ParentModel = Backbone.Model.extend 

ParentCollection = Backbone.Collection.extend 

CollectionA = ParentCollection.extend 
    model: ModelA 

CollectionB = ParentCollection.extend 
    model: ModelB 

CollectionC = ParentCollection.extend 
    model: ModelC 

ModelA = ParentModel.extend 
    defaults: 
     collectionB: new CollectionB() 
     collectionC: new CollectionC() 

ModelB = ParentModel.extend 
    defaults: 
     collectionA: new CollectionA() 

ModelC = ParentModel.extend 
    defaults: 
     collectionA: new CollectionA() 

ModelA有兩個帶'小孩'模型的集合。 ModelB和ModelC反之亦然:帶有「父」模型的一個集合。 ModelA工作正常,但ModelB和ModelC會產生兩個錯誤。第一個是Firebug的spy.js:「Module name'modelB'尚未加載上下文:_」,第二個加入了Require.js:「模塊名'collectionB'尚未加載上下文:_」。如果我沒有加載模型B和C中的集合,那麼沒有錯誤並且應用程序可以正常工作。我正在嘗試解決這個錯誤,但我不知道發生了什麼問題。它是一個Backbone.js循環引用問題還是一個Require.js循環依賴或者其他的東西?

編輯

代碼organisation.coffee(MODELA)

define (require) -> 
    _ = require 'underscore' 
    mGroup = require 'models/object/group/group' 
    cDepartement = require 'collections/object/group/departement' 
    cProject = require 'collections/object/group/project' 

    mGroup.extend 
     'urlRoot': '/api/organisation' 
     'defaults': _.extend({}, mGroup.prototype.defaults, 
      'type': 'organisation' 
      'departements': new cDepartement() 
      'projects': new cProject()) 

代碼project.coffee(modelB)

define (require) -> 
    _ = require 'underscore' 
    mGroup = require 'models/object/group/group' 
    cOrganisation = require 'collections/object/group/organisation' 

    mGroup.extend 
     'urlRoot': '/api/project' 
     'defaults': _.extend({}, mGroup.prototype.defaults, 
      'type': 'project' 
      'organisations': new cOrganisation()) 

如果我註釋掉cOrganisation =需要...和新的組織而不是一切正常。項目,部門和組織都是團體,但組織是項目和部門的父母。

+0

你可以發佈一些你需要的代碼嗎?所以我可以更多地瞭解你的問題 – 2012-07-16 13:57:54

回答

1

是的。只需將默認值移至initialize方法即可。在加載所有定義時將使用它。例如:

ModelB = ParentModel.extend 
    initialize(options) -> 
    options = options || {} 
    if options.collectionA 
     this.collectionA = options.collectionA 
    else 
     this.collectionA = new CollectionA() 
相關問題