jlbriggs
jlbriggs

Reputation: 17791

Highcharts / jQuery - destroy and rebuild chart with original options

Based on info in this thread: Implement own state - INACTIVE_STATE?

I have built a chart that fits my needs - jsfiddle

I added some custom controls to allow the user to show/hide all series and to check/uncheck all series.

These all work fine.

The last part that I want to do is allow the user to reset the chart with the original options.

This part I also got working, but there is a problem: once the chart is rebuilt, the functions that allow the user to show/hide/check/uncheck no longer work because I have destroyed and re-specified the variable that they run off of.

So my question(s) -

  1. is this the right way to destroy and rebuild the chart, or is there a better method?
  2. if this is the way to do it, then how do I get my show/hide/check/uncheck functions to continue to work afterward?

The code to reset the chart is here:

//reset the chart to original specs
$('#resetChart').click(function(){
    chart1.destroy();
    chart1 = new Highcharts.Chart(optionsChart1,highlightSer);
});

highlightSer is a call back function to highlight certain series.

an example of the code which no longer works afterward:

var chart = chart1;
$('#showAll').click(function(){
        for(i=0; i < chart.series.length; i++) {
        chart.series[i].show();
    }
});

thanks!

Upvotes: 10

Views: 47830

Answers (2)

Bhesh Gurung
Bhesh Gurung

Reputation: 51030

1) is this the right way to destroy and rebuild the chart, or is there a better method?

That's the only way and Highcharts is smart enough so that you don't have to worry about any memory leaks.

2) if this is the way to do it, then how do I get my show/hide/check/uncheck functions to continue to work afterward?

You are recreating the chart but not assigning it to the variable chart again.

$('#resetChart').click(function(){
    chart1.destroy();
    chart1 = new Highcharts.Chart(optionsChart1,highlightSer);
    chart = chart1; // <-------- Add this line here.
});

Upvotes: 17

polarblau
polarblau

Reputation: 17734

Is there a reason for assigning the chart to a new variable here?

var chart = chart1;

chart will not point to a graph anymore after you have destroyed it. If you just use chart1, which you re–assign, everything seems to work just fine. Or am I missing something?

Upvotes: 3

Related Questions