如何获取先前创建的 Google 图表的实例?

How to get the instance of a previously created Google Chart?

我有一个使用 Google 图表的 Web 应用程序。 一页上有多个图表。 我成功创建并渲染了图表。

根据用户的过滤器,我通过 Ajax 接收新的图表数据。 如果我没有将返回的对象保留在代码中那么远,我该如何重新获取图表对象并更新它?

我不会做类似下面的事情:

function DrawChart()
{
  // Code code code ... more code

  // Initialize
  var chart = new google.visualization.ScatterChart(document.getElementById("my-chart-div"));
  // Draw
  chart.draw(data, options);
}

稍后:

function UserDidSomething()
{
    var newData = MyAjaxCall(...);
    var options = ...;
                             
    var chart = ...; // What goes here??
                             
    chart.draw(newData, options);
}

提前致谢, 害羞。

我创建了一个动态 charts 对象来保存创建的图表:

/// <summary>
/// This object holds created charts in order to edit them.
/// The key for the chart is the div id (e.g. charts["chart-my-chartname"]).
/// </summary>
var charts = {};

function ChartCreated(divId)
{
    return charts[divId] !== undefined && charts[divId] != null;
}

function GetChart(divId)
{
    return charts[divId];
}

function AddChart(divId, chart)
{
    charts[divId] = chart;
}

function RemoveChart(divId)
{
    charts[divId] = null;
}

function CreateOrUpdateChart(divId, chartType, data, options)
{
    var chart;

    // If the chart was previously created, use its object
    if (ChartCreated(divId))
    {
        chart = GetChart(divId);
    }
    else // If there was no chart, create and keep it
    {
        chart = InitializeNewChart(chartType, divId);
        AddChart(divId, chart);
    }

    // Create a new DataTable object using the JavaScript Literal Initializer, and the received JSON data object
    data = new google.visualization.DataTable(data);

    // Render chart
    chart.draw(data, options);
}

function InitializeNewChart(type, divId)
{
    var container = document.getElementById(divId);

    switch (type)
    {
        case "Scatter": return new google.visualization.ScatterChart(container);
        case "Column": return new google.visualization.ColumnChart(container);
        case "Line": return new google.visualization.LineChart(container);
        default: return null;
    }
}