简体   繁体   中英

Uncaught ReferenceError: chart is not defined when using two charts

I am displaying two Highcharts on the same page based on different data sets.

I am trying to apply a common function to both of them.

The common function that I am using in both charts is given below:

(function(H) {
    H.wrap(H.Series.prototype, 'getClipBox', function(proceed, animation, finalBox) {
        var result = proceed.apply(this, Array.prototype.slice.call(arguments, 1));

        if (finalBox) {
            return {
                x: 0,
                width: this.chart.plotWidth
            }
        }

        return result;
    });
}(Highcharts));

The way I am using the fuction is that I have created two script tags on the same page under which the two charts' data is processed.

Like the following:

Chart 1:

<script>
(function(H) {

    //The Above Code

    }(Highcharts));

    var chart = Highcharts.chart('ecg', {

    // the Chart Code
});

var delay = drawAnimationDuration / chart.plotWidth * chart.plotSizeX;

</script>

Chart2:

<script>
(function(H) {

    //The Same code Above

    }(Highcharts));

    var chart = Highcharts.chart('ppg', {

    // the 2nd Chart Code
});

var delay = drawAnimationDuration / chart.plotWidth * chart.plotSizeX;

</script>

Note: drawAnimation variable is defined for both the Charts.

The first chart is working fine, but the second chart is throwing the error:

Uncaught ReferenceError: chart is not defined at Object.success (:211:38)

Which redirects to this line above:

var delay = drawAnimationDuration / chart.plotWidth * chart.plotSizeX;

I have added a fiddle also. The fiddle is showing no data, but if I remove the function and run the functions directly, then it works. Fiddle:

https://jsfiddle.net/abnitchauhan/4terfoup/14/

You are making a big mistake, you have to know what scope is in javascript, and how and where variables are visible in code. A quick guide to what scope is in JS:

let data = 'Example variable';
function firstFunction(){
  let nextVariable;

  //Here you can access to data and nextVariable
}

function firstFunction(){
  let thirdVariable;

  //Here you can access to data and thirdVariable
}

//But here in our global scope we only have access to the data variable because nextVariable and thirdVariable are in their own local scopes and you can't access them in the outside scope.

And in your example you have the same problem. You have defined chart and drawAnimationDuration only in the ecgData function so the ppgData function doesn't have access to these variables.

A working fiddle: https://jsfiddle.net/zbdga4r6/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM