lucasboleli
lucasboleli

Reputation: 61

How to handle cyclic references in ThrustJS?

We have a class A that references class B , and class B references class A which creates a loop on instance time while require clause is called, how can I handle this using ThrustJS ? ( we don't have it handled by the framework like in NodeJS).

Upvotes: 0

Views: 40

Answers (2)

lucasboleli
lucasboleli

Reputation: 61

My solution was to require B inside method , preventing the ciclic reference when the class is instanciated.

class A {
    testA(){
        const b = require('b')
        b.testB()
    }
}
class B {
    testB(){
        const a = require('a')
        a.testA()
    }
}

Upvotes: 0

Älskar
Älskar

Reputation: 2577

If you have no other recourse of getting rid of cyclic references by completely removing either the reference from A to B or from B to A.

Then one solution is to create an intermediate/proxy module or class which is, depending on your requirements, a composition or aggregation of classes A and B.

Given:

class A {
  b = new B();
}

class B {
  a = new A();
}

Then, removing the cyclic references:

class A {
  // some stuff
}

class B {
  // some other stuff
}

class AB {
  a = new A();
  b = new B();
}

const ab = new AB();
ab.a;
ab.b;

Upvotes: 1

Related Questions