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:

  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});

Author: Fantashit

2 thoughts on “How to use Destroy() – yes I read the other posts :)

  1. 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});
    
  2. 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
    }

Comments are closed.