1

I have a CommonJS module:

// main-module
module.exports = function () {
  var foo,
      someModule = require('other-module')(foo);

  // A value is given to foo after other-module has been initialised
  foo = "bar";
}

As you can see, this requires other-module:

// other-module.js
module.exports = function (foo) {
  function example() {
    console.log(foo);
    // > "bar"
  }
}

I would like the example function inside of other-module to be aware of the foo variable inside of main-module, even though is it established after the module is required.

When other-module runs, foo will not be undefined. However, the point is that by time my example function runs, foo will have been given a value of bar.

The pattern above obviously does not work. What design pattern do I need to implement?

2 Answers 2

2

I'm not super-familiar with CommonJS, so this might not be the idiomatic way to do it, but using a function instead of a variable should work:

// main-module
module.exports = function () {
  var foo,
      someModule = require('other-module')(function() { return foo; });

  foo = "bar";
}

// other-module.js
module.exports = function (fooFn) {
  function example() {
    console.log(fooFn());
  }
}
Sign up to request clarification or add additional context in comments.

Comments

0

The foo value (a string) will be passed by value, so it's undefined inside other-module. You could use an options object that is passed by reference:

var options = {},
someModule = require('other-module')(options);

options.foo = "bar";

2 Comments

@OliverJosephAsh change options = {"foo": "bar"}; to options.foo = 'bar'; and it will.
Thanks @MattBall, you're right. If we assign a new value to options we have the same problem as when we passed the string by value - so we need to keep the options reference the same.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.