I'm new to javascript and I'm confused at how variable scoping works. I have a leaflet js map that has multiple markers on it that show the windfarm name as a pop up when clicked. My goal is when the marker is clicked, to post this name to the flask server and return the wind speeds and wind power for that windfarm. This part works fine. I have two radio buttons that when selected changed the data set displayed on a chartjs map between wind speeds or wind power. The difficulty I am having here is when I try to add an event listener function to the radio buttons, I need to pass arguments into the "updateChartData" function for the wind speeds and wind power datasets. I have declared these datasets inside the "clickMarker" function but they are scoped to this function. How do I pass these datasets into "updateChartData" function? Please see code below:
function clickMarker(e) {
let timestamp_values = [];
let windspeed_values = [];
let windpower_values = [];
console.log(e)
let windfarmName = e.target._popup._content
const lookup_url = {{ url_for('lookup')|tojson }}
let data = {"Windfarm": windfarmName}
fetch(lookup_url, {
"method": "POST",
"headers": {"Content-Type": "application/json"},
"body": JSON.stringify(data),
})
.then(function(response){
return response.json();
})
.then(function(json){
console.log(json);
// Loop through the objects returned by server to get each object data and then add timestamps and windspeeds to an array
for (const element of json) {
timestamp_values.push(element.timestamp);
windspeed_values.push(element.windspeed);
windpower_values.push(element.windpower);
};
// Populate windChart x and y values with data
windChart.data.labels = timestamp_values
windChart.data.datasets[0].data = windspeed_values
// Update the windchart with the new data rather than adding another layer everytime function is called
updateChartData(windspeed_values, windpower_values)
})
};
// Get the windpower values
// Function to update chart data based on selected radio button
function updateChartData(windspeeds, windpowers) {
let selectedDataSet = document.querySelector('input[name="dataSet"]:checked').value;
if (selectedDataSet === 'Windspeeds') {
windChart.data.datasets[0].data = windspeeds;
windChart.data.datasets[0].label = 'Wind Speed';
} else if (selectedDataSet === 'Windpowers') {
windChart.data.datasets[0].data = windpowers;
windChart.data.datasets[0].label = 'Wind Power';
}
// Update the windchart with the new data rather than adding another layer everytime function is called
windChart.update();
}
// // Add event listener to radio buttons
let radioButtons = document.querySelectorAll('input[name="dataSet"]');
radioButtons.forEach(function (radioButton) {
console.log(windspeed_values)
radioButton.addEventListener('change',updateChartData(windspeed_values, windpower_values) )
});