使用Backbone.js和Require.js在模型中引用集合的循环

时间:2012-07-15 19:04:00

标签: 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:“模块名称'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 = require ...和新的组织,那么一切都有效。项目,部门和组织都是团体,但组织是项目和部门的父母。

1 个答案:

答案 0 :(得分:1)

是。只需将默认值移至initialize方法即可。在加载所有定义时将使用它。类似的东西:

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