如何将一个函数中定义的变量作为参数传递给 Javascript 中的 addEventListener 函数?

问题描述 投票:0回答:1

我是 javascript 新手,我对变量作用域的工作原理感到困惑。 我有一个传单 js 地图,上面有多个标记,单击时会弹出风电场名称。我的目标是当单击标记时,将此名称发布到 Flask 服务器并返回该风电场的风速和风力。这部分工作正常。我有两个单选按钮,选择它们后会更改 Chartjs 地图上显示的风速或风力之间的数据集。我在这里遇到的困难是,当我尝试向单选按钮添加事件侦听器函数时,我需要将风速和风力数据集的参数传递到“updateChartData”函数中。我已在“clickMarker”函数内声明了这些数据集,但它们的范围仅限于此函数。如何将这些数据集传递到“updateChartData”函数中?请看下面的代码:

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) )
    });
javascript function addeventlistener scoping
1个回答
0
投票

为了在单选按钮更改时将数据集(windspeed_values 和 Windpower_values)传递到 updateChartData 函数中,您需要进行一些修改。一种方法是将数据集定义为 clickMarker 函数外部的变量,使它们可以在整个脚本中访问。

© www.soinside.com 2019 - 2024. All rights reserved.