I've broken down my source code so that certain classes are responsible for creating and updating key objects in my application. The trouble is when I move those objects into separate modules and they are updated outside of the module, other modules do not reflect the updated object because it's not aware of the changes which have happened outside of the module.
For example below is a simplified example:
// config.js
class Config {
constructor() {
this.value = false
}
set(value) {
this.value = value
}
}
const config = new Config()
export default config
//output.js
import config from './config'
console.log(config.value) // -> false
// Use the config to return a new value
class Output {
constructor() {
this.data = config.value
}
}
const output = new Output()
export default output
//index.js
import config from './config'
import output from './output'
config.set(true) // Value set by user of application
console.log(config.value) // -> true
console.log(output.data) // -> false
I know why this doesn't work as I want, but I don't know how to I should be dealing with this situation. Currently, the only way I can think to get around this issue is to pass the updated object to each class as a parameter of its constructor. However, in my actual application, it's much more complicated than this example and it gets very messy having to import the updated object into each class or function which needs it.
You can see an example of the actual source code where I am passing config, theme and data through the constructor to get around it.
What's the better way to deal with this issue?
this.data = config.valuethis line is your problem.config.valueis a boolean, which is copied by value on write. It doesn't hold the reference to the config object. This has nothing to do with imports/exports. Also please don't used reserved key words as method names, that's asking for trouble.let foo = xif x evaluates to a primitive type the value of foo is determined on assignment (write). But if x is a reference type, then foo is a reference to x and what value foo has is determined when it is dereferenced (read). And it doesn't matter if it's x or x.someProperty, the same rules apply.