I've run into a problem that may have to do with my lack of understanding of the use of exports
/ RequireJS for circular dependencies.
I'm getting the error relatedModel does not inherit from Backbone.RelationalModel
.
On to the code (in CoffeeScript; I hope that's alright)...
I have two Backbone Models / RequireJS modules, FooModel and BarModel:
FooModel:
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
BarModel:
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
I have also tried:
- Extending
FooModel
fromBackbone.Model
instead ofBackbone.RelationalModel
and creating thetheBars
collection myself (inparse
and in custom function). (BarModel
has aHasOne
relation of a another model, so I need it to still be aRelationalModel
.
Is this possibly a problem with the way exports
works? As far as I understand, exports
just provides an object to hang module objects on so the modules are accessible elsewhere. Is the error occurring because the BarModel
isn't actually a Backbone Model at the point in the FooModel
code where I define relations?
Update
I seem to have solved my issue, although I'm unsure how. Can't say I'm pleased about not understanding why it's working, but I sure am pleased that it is working. Also see my comment about _.memoize
below in the BarModel
code.
(Before I got the code below to work, I created a workaround whereby I created the associated collection in FooModel
's parse
function and exported BarModel
. However, the response of require 'collections/foos'
returned an object like so: {FooCollection: <Backbone.Collection Object>}
, i.e. it was unexpectedly wrapped in another object.)
Here's the updated code:
FooModel:
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
BarModel:
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