グラフ分析のためにcytoscape.jsのElectronアプリを開発しました。現在、私はコードベースのリファクタリングと外部モジュールへの関数の移動を行っています。現在、私は可変スコープと戦っています。エレクトロン、変化するグローバル変数を外部モジュールに公開する
- 私は、ユーザーがグラフとやりとりするときに変化するいくつかの変数を持っています。
- 解析の種類によって異なるUI(ボタン)が読み込まれます。
問題:変数の最近の値を、コードを簡略化する方法でモジュールに渡すことはできません。
次のコードは、コアの問題を示しています。
// 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
}
モジュールは、私が何をしたいのか、次のコード
// module.js
module.exports = function printValue (value) {
const button = document.getElementById('button-id')
button.addEventListener('click',() => {
console.log(value)
})
}
を持って、モジュール内の各コンフィギュレーションのボタンの宣言と関連する機能を移動することです。次に、ユーザーが選択したアプリの設定に基づいてこれらのモジュールを呼び出します。
'selectedNode'は、プリミティブ型(文字列)のようですので、あなたがあなたのモジュールに渡したときに、それが現時点で持っていた値を使用するに変更されました
。あなたは 'selectedNode = {}'を変更し、 'selectedNode.value = selection.target [0]'で値を変更し、 'printValue(selectedNode)'で渡し、あなたのモジュールで 'selectedNode.value'実際の現在の値を取得します。 (キーワード:pass-by-valueと参照渡し) 'printValue'を呼び出すたびにリスナーをボタンに追加します。しばらくすると、そのボタンをクリックすると複数のconsole.logが終了します。 – RoyalBingBong