【问题标题】:Circular referencing a collection in a model with Backbone.js and Require.js使用 Backbone.js 和 Require.js 循环引用模型中的集合
【发布时间】:2012-07-26 16:52:33
【问题描述】:

我有以下设置(伪咖啡代码)。模型和集合使用 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 循环依赖或其他问题?

编辑

organization.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... 和新的 cOrganisation,那么一切正常。项目、部门和组织都是团体,但组织是项目和部门的父级。

【问题讨论】:

  • 你能发布一些你需要的代码吗?这样我就可以深入了解您的问题

标签: backbone.js


【解决方案1】:

是的。只需将默认值移动到 initialize 方法即可。加载所有定义时将使用它。比如:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 2014-05-28
    • 1970-01-01
    相关资源
    最近更新 更多