Tyler Tyler - 2 years ago 128
Ajax Question

Dynamically calling a constructor with Google Visualizations?

I'm working with Google Visualizations and I'm trying to sort something out. This seems simple to me but I can't seem to find the right documentation for Javascript nor in the Google documentation that would give me a clear idea how to do this.

Right now I have a function in my js file that looks like this:

function drawChart(raw,columns,options,chart) {
var data = new google.visualization.arrayToDataTable(JSON.parse(raw));
var view = new google.visualization.DataView(data);
chart.draw(view, options);

Which looks well and good except for one pesky problem with the constructor

Take a look at an example call of the function:

drawChart(grabarray("?warid="+warid+"&type=0"),[0, 1,{ calc: "stringify", sourceColumn: 1,type: "string",role: "annotation" },2],
title: "Attempted actions by player",
},new google.visualization.BarChart(destination);

(Note AJAX is being done properly but I cut it to make the example make more sense)

As you can see above I'm forced to have the following line directly in the javascript:

new google.visualization.BarChart(destination)

When I would like to just have the value "BarChart" included in my AJAX return so I could do something like this

new google.visualization("BarChart",destination)

This would enable me to call create other google visualizations all using the same drawChart function.

TL:DR, how can I call a constructor dynamically to achieve this:

new google.visualization("BarChart",destination)
new google.visualization("PieChart",destination)
new google.visualization("LineGraph",destination)

Answer Source

try it like this...

new google.visualization["BarChart"](destination)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download