我有一个使用Google Charts的Web App。 页面上有多个图表。 我成功地创建并渲染了图表。
根据用户的过滤器,我通过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);
}
提前致谢, 害羞。
答案 0 :(得分:2)
我创建了一个动态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;
}
}
&#13;