Reputation: 1408
I'm trying to figure out chartjs' destroy method and it's not working quite right. I'm doing this on dummy data with a dummy button, but here's what I have.
Really simple html markup for testing:
<div class="container mt-5">
<div class="row">
<canvas id="myChart"></canvas>
</div>
<div class="row mt-5">
<button class="btn btn-primary" id="chartBTN">Next Chart</button>
</div>
</div>
Simple js below. The point is that a chart is generated on load, then, on button click, the chart adds another data set to it for comparison. To do that, I understand I have to destroy the first chart to recreate the second. Testing the button click works, but the chart destroy doesn't do anything. Instead, I get an error.
Am I putting the destroy method in the wrong place?
// Our labels along the x-axis
var years = [1500,1600,1700,1750,1800,1850,1900,1950,1999,2050];
// For drawing the lines
var africa = [86,114,106,106,107,111,133,221,783,2478];
var asia = [282,350,411,502,635,809,947,1402,3700,5267];
var europe = [168,170,178,190,203,276,408,547,675,734];
var latinAmerica = [40,20,10,16,24,38,74,167,508,784];
var northAmerica = [6,3,2,2,7,26,82,172,312,433];
var ctx = $("#myChart");
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: years,
datasets: [
{
data: africa
}
]
}
});
$('#chartBTN').on('click', function(){
myChart.destroy();
var ctx = $("#myChart");
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: years,
datasets: [
{
data: africa,
label: 'Africa',
borderColor: "#3e95cd",
fill: false
},
{
data: asia,
label: "Asia",
borderColor: "#3e95cd",
fill: false
}
]
}
});
});
Upvotes: 2
Views: 5047
Reputation: 19224
A variable declared with var
is hoisted to the top of the function. You are declaring the same variable again in the function.
So the function declaration is hoisted to top of function where it is undefined.
Hence, myChart.destroy()
is undefined.
https://developer.mozilla.org/en-US/docs/Glossary/Hoisting
Instead of actually destroying the instance, you should update the instance instead.
myChart.data.datasets = [] //Desired Data
myChart.update();
If you want to go with destroying the instance, you can remove the var
declaration from inside the function and it should work fine. (since the variable is already defined in scope of that function.
Upvotes: 2