Chart.js icon indicating copy to clipboard operation
Chart.js copied to clipboard

How to use Destroy() - yes I read the other posts :)

Open shoupjom opened this issue 11 years ago • 18 comments

I've seen this mentioned about a dozen times so I'm either missing something obvious or my use case is different. Order of events:

  1. Create canvas in html
  2. Select option from pick list in html
  3. Use pick list's 'onchange' event plus the selected value to trigger a SOAP call to server
  4. Parse XML from SOAP response and convert values into Chart's data object
  5. Create new chart Note: Steps 3-5 are performed within the same javascript function Note: Steps 3-5 are ALSO performed for each subsequent change to the pick list selection

Problem: When a user selects a NEW value from the pick list a new chart is rendered on the canvas, but as others have mentioned the original chart still exists underneath the new chart - which causes all sorts of issues when you mouse over the chart. SO, how do I destroy the old chart since the function that created it has lost context and then gets re-called? I tried adding a destroy() before the chart gets created...but in this scenario, within the second function call, myNewChart1 has not been instantiated right? So confused....

myNewChart1.destroy(); var doc1 = document.getElementById("stockPrice"); var ctx1 = doc1.getContext("2d"); var myNewChart1 = new Chart(ctx1).Line(barChartData1, {animation: false});

shoupjom avatar Mar 18 '15 13:03 shoupjom

I've also got a similar issue. Created charts within a function causes all sorts of issues. It will create charts just fine, but all sorts of memory issues occur when not destroyed.

bluesodium avatar Mar 18 '15 20:03 bluesodium

Yeah I am having the same issue to... Any help would be great!

Thanks

kevinkashou avatar Mar 18 '15 22:03 kevinkashou

@shoupjom you need to capture the chart variable somewhere. If you lose it, you cannot destroy it obviously.

etimberg avatar Mar 19 '15 22:03 etimberg

FINALLY figured this out.... I admit I'm brand new to html/css/js.

I was struggling with how to make the chart variable global. Since other's have obviously had the same problem, here's the answer.

I changed my new chart variable from... var myNewChart1 = new Chart(ctx1).Line(barChartData1, {animation: false}); TO window.myNewChart1 = new Chart(ctx1).Line(barChartData1, {animation: false});

This adds the chart object as an attribute to the window object which is a global object. Then when the function is called a second time, myNewChart1 is still in scope/instantiated.

Then I added some null checking as follows... if(window.myNewChart1 != null){ window.myNewChart1.destroy(); }

This way, destroy() is only executed if we've already created the chart the first time. So the entire block of code looks like...

if(window.myNewChart1 != null){
    window.myNewChart1.destroy();
}

var doc1 = document.getElementById("stockPrice");
var ctx1 = doc1.getContext("2d");
window.myNewChart1 = new Chart(ctx1).Bar(barChartData1, {animation: false});

shoupjom avatar Mar 20 '15 02:03 shoupjom

I to am doing window.bar but I have multiple charts and it is using that same variable but of a new instance of it. In the console.log I get "TypeError: window.bar is undefined". I have no clue why :/

I screenshot my code.... any help would be great! screen shot 2015-03-19 at 7 41 43 pm

kevinkashou avatar Mar 20 '15 02:03 kevinkashou

Nothing is jumping out at me but like I said, I'm new to JS. Have you tried not using strict mode by chance?

shoupjom avatar Mar 20 '15 02:03 shoupjom

Not sure if I follow with not using strict mode?

kevinkashou avatar Mar 20 '15 07:03 kevinkashou

I have a loop below that creates charts from an ajax call and loops through the data creating multiple charts in predefined canvases. How can i make sure that the previous charts is/are destroyed if I am using the same variable name in the function (as obviously a new chart object is created each time it gets called)?

I can't even use update as there is no object variable to target...

function doLineChart(id,axis,labels,dataset) { var chartjsData,chartjsLabels; var lineData; var lineOptions; var myLine; var fontList = "'Segoe UI', 'Helvetica', 'Arial', sans-serif"; chartjsData = dataset; chartjsLabels = labels; lineData = { labels :chartjsLabels, datasets : [ { fillColor: "rgba(151,187,205,0.2)", strokeColor: "rgba(151,187,205,1)", pointColor: "rgba(151,187,205,1)", pointStrokeColor: "#fff", pointHighlightFill: "#fff", pointHighlightStroke: "rgba(151,187,205,1)", data : chartjsData, } ] }; lineOptions = { animation:false, pointHitDetectionRadius : 3, canvasBackgroundColor : "white", maintainAspectRatio:true, responsive:true, scaleFontColor:"#333", scaleFontFamily:fontList, tooltipFontFamily:fontList, tooltipTitleFontFamily:fontList, }; myLine = new Chart(document.getElementById("canvas_"+id).getContext("2d")).Line(lineData,lineOptions);
$('#canvas_label_'+id).html(""+axis+""); //console.log(myLine); }

bluesodium avatar Mar 20 '15 11:03 bluesodium

@bluesodium you could use a map indexed by the canvas ID. If you only need to support the most modern browser you can use the ES6 map.

etimberg avatar Mar 20 '15 11:03 etimberg

@etimberg - what do you mean by using map indexed by canvas ID to use the destroy function?

kevinkashou avatar Mar 20 '15 20:03 kevinkashou

Alright I found the solution instead of doing window.bar since I was doing prototype of each instance of the charts I referred it with this.bar instead of window.bar. Thanks for everyone's help!

kevinkashou avatar Mar 20 '15 20:03 kevinkashou

@shoupjom Thank you so much buddy boy, that probably saved me a lot of time, and was driving me nuts!!

joethejones avatar Nov 18 '15 16:11 joethejones

@shoupjom Thanks, buddy! This actually helped me a lot. Just one note that In my case I also had to check if the window.chart has been defined for the first occurrence.

    if(window.chart && window.chart !== null){
        window.chart.destroy();
    }

But rest of the code did the thing. Thank you

ponyczek avatar Feb 20 '18 23:02 ponyczek

To check if instance of chart is already on var window.chart use if(window.chart instanceof Chart){ window.chart.destroy; // the destroy without ( ). cause it is not function to call but just instance }

marino-andriamialy avatar Feb 18 '20 09:02 marino-andriamialy

This worked for me. Thank you!

    if(window.myChart instanceof Chart)
    {
        window.myChart.destroy();
    }

Suryakumar007 avatar Apr 25 '20 15:04 Suryakumar007

This worked for me. Thank you!

    if(window.myChart instanceof Chart)
    {
        window.myChart.destroy();
    }

Thanks so much for posting this @Suryakumar007! Your solution solved my issue as well.

aboestpetersen avatar May 28 '21 08:05 aboestpetersen

 destroyCharts(): void {
    for(let i=0;i<this.charts.length;i++){
      console.log(this.charts[i]);
      this.charts[i].destroy();
    }
  }

I am deleting multiple charts depending upon the page size, and recreating them, But I am getting error: "this.charts[i].destroy is not a function at ChartsComponent.destroyCharts (charts.component.ts:116:22)"

shishirTelesoft avatar Dec 22 '23 07:12 shishirTelesoft

if (window.submissionChart && typeof window.submissionChart.destroy === 'function') { window.submissionChart.destroy(); // Safely destroy the previous instance }

This worked for me

physicshaurya avatar Oct 27 '24 17:10 physicshaurya