我遇到了一个问题,这可能与我对使用exports
/ RequireJS 进行循环依赖缺乏了解有关。
我得到了错误relatedModel does not inherit from Backbone.RelationalModel
。
关于代码(在 CoffeeScript 中;我希望没问题)......
我有两个主干模型/RequireJS 模块,FooModel 和 BarModel:
Foo型号:
define (require) ->
Backbone = require 'backbone'
BarModel = require 'models/bar'
FooModel = Backbone.RelationalModel.extend
relations: [
type: Backbone.HasMany
key: 'theBars'
relatedModel: BarModel # <-- this is where the BB Relational error is coming from
]
return FooModel
酒吧型号:
define (require, exports) ->
Backbone = require 'backbone'
FooCollection = require 'collections/foos'
BarModel = Backbone.RelationalModel.extend
someFunction: ->
# uses FooCollection
# I've tried moving the require in here and getting rid of exports
exports.BarModel = BarModel
return BarModel # I've tried with and without this line, but CS just returns the last line anyway so removing it is functionally the same
我也试过:
- 扩展
FooModel
而Backbone.Model
不是自己Backbone.RelationalModel
创建theBars
集合(在自定义函数中parse
和自定义函数中)。(与另一个模型BarModel
有HasOne
关系,所以我需要它仍然是RelationalModel
.
这可能是exports
工作方式的问题吗?据我了解,exports
只是提供一个对象来挂模块对象,以便模块可以在其他地方访问。发生错误是因为在我定义关系BarModel
的代码中实际上不是主干模型吗?FooModel
更新
我似乎已经解决了我的问题,虽然我不确定如何。不能说我很高兴不理解它为什么起作用,但我确实很高兴它起作用了。另请参阅我在代码_.memoize
下方的评论。BarModel
(在我让下面的代码工作之前,我创建了一个解决方法,我在FooModel
的parse
函数中创建了关联的集合并导出BarModel
了。但是,require 'collections/foos'
返回的响应是这样的:{FooCollection: <Backbone.Collection Object>}
,即它意外地包装在另一个对象中。)
这是更新的代码:
Foo型号:
define (require) ->
Backbone = require 'backbone'
BarModel = require 'models/bar'
BarCollection = require 'collections/bars'
FooModel = Backbone.RelationalModel.extend
relations: [
type: Backbone.HasMany
key: 'theBars'
relatedModel: BarModel
collectionType: BarCollection
]
return FooModel
酒吧型号:
define (require, exports) ->
Backbone = require 'backbone'
BarModel = Backbone.RelationalModel.extend
someFunction: -> #this actually used to use _.memoize (sorry for the incomplete code), so maybe it would have tried to run the function argument immediately?
# uses FooCollection
FooCollection = require 'collections/foos'
return AttributeModel