1

I have a few files that export an object to be reused as models. Within some objects I use a model from another file. This works fine as long as the other model doesn't use the other file, but if they do then one becomes undefined. I figure this is because of a cyclic reference and therefore to avoid mayhem it scraps one of the references.

Here's a dumbed down example:

a.js

import b from './b.js'

export default {
  a: b
}


b.js

import a from './a.js'

export default {
  b: a
}

Is this possible in any way?

James
  • 1,045
  • 8
  • 17
  • I don't know that much about modules, but the above looks like a chicken/egg situation. This may break what you're using with an infinite loop. – Jack Bashford Feb 01 '19 at 05:29
  • Yeah, that's what I figure as well. But perhaps someone has a trick up their sleeve ;) – James Feb 01 '19 at 05:30
  • What is the expected result? – guest271314 Feb 01 '19 at 05:36
  • But why would you want to do this? Circular dependencies are never good. Why not create an intermediate module in which you import both `a` and `b` and and export whatever composition of those two you want? – ethane Feb 01 '19 at 05:50
  • @guest271314 Just to have objects that may contain another object. Each export actually has a number of other properties, but some properties share the same data model so it would be nice to be able to reuse them. – James Feb 01 '19 at 05:50
  • @ethane Makes sense and could be a solution. Perhaps I'll expand on my original question with a larger example – James Feb 01 '19 at 05:52
  • @james.brndwgn - take a look at this Plunker. I'm not sure if this is what you are trying to do. Modules, being independent from one another abstract away the idea of sharing data. The easiest, and most common way to share data between modules is the have a module act as a singleton. So in the Plunker, the `singleton.js` file is the shared model. The `other.js` files is some other module that needs to share that data. You'll see all three `js` files modifying the data in the model and all three have reference to the shared model: http://plnkr.co/edit/dsEWxlEC8GfzeX1s10x7?p=preview – Randy Casburn Feb 01 '19 at 05:52
  • @RandyCasburn Gotcha. I think this answers my question. The cyclic dependency is the issue and so I'd have to break apart any nested models. – James Feb 01 '19 at 05:56
  • You could also extend from a base class or set an ordinary JavaScript Constructor function's prototype to the imported object too. The idea is the Model was instantiated as the export - this makes it a singleton so all share the same data. – Randy Casburn Feb 01 '19 at 05:58

0 Answers0