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

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

本文关键字:创建 Google 实例 何获取 获取      更新时间:2023-09-26

我有一个使用谷歌图表的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;
    }
}