How to use Destroy() - yes I read the other posts :)
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:
- Create canvas in html
- Select option from pick list in html
- Use pick list's 'onchange' event plus the selected value to trigger a SOAP call to server
- Parse XML from SOAP response and convert values into Chart's data object
- 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});
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.
Yeah I am having the same issue to... Any help would be great!
Thanks
@shoupjom you need to capture the chart variable somewhere. If you lose it, you cannot destroy it obviously.
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});
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!

Nothing is jumping out at me but like I said, I'm new to JS. Have you tried not using strict mode by chance?
Not sure if I follow with not using strict mode?
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 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 - what do you mean by using map indexed by canvas ID to use the destroy function?
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!
@shoupjom Thank you so much buddy boy, that probably saved me a lot of time, and was driving me nuts!!
@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
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 }
This worked for me. Thank you!
if(window.myChart instanceof Chart)
{
window.myChart.destroy();
}
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.
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)"
if (window.submissionChart && typeof window.submissionChart.destroy === 'function') { window.submissionChart.destroy(); // Safely destroy the previous instance }
This worked for me