I have developed an Electron app with cytoscape.js for graph analysis. Currently, I am in the process of refactoring the code base and moving functions to external modules. Currently I am battling with the variable scope.
- I have a number of variables that change when a user interacts with a graph.
- I load different UIs (buttons) depending on the type of analysis.
Issue: I cannot pass the recent value of a variable to a module in a way that will simplify the code.
The following code shows the core issue.
// app.js
// require the module
const printValue = require('./printValue.js')
// global variable that I want to access
let selectedNode = ''
// called when a user clicks on node on the graph
cytoscape.on('tap', 'node', selection => {
// stores the node's data
selectedNode = selection.target[0]
// I wan't to avoid that, since I load different configurations
printValue(selectedNode) // prints the most recent value
})
// loads the different buttons
if (configuration === '1') {
// I want to transfer it to an external module
const button = document.getElementById('button-id')
button.addEventListener('click', () => {
console.log(selectedNode) // prints the most recent value
})
// I want to make this part work
printValue(selectedNode) // prints '', the initial value of the variable
} else if (configuration === '2') {
// loads different buttons with different functions
}
The module has the following code
// module.js
module.exports = function printValue (value) {
const button = document.getElementById('button-id')
button.addEventListener('click', () => {
console.log(value)
})
}
What I want to do, is to move the button declarations and related functions of each configuration in modules. Then call those modules based on the app configuration the user has selected.