JavaScript Template Strings

54 views
Skip to first unread message

Ray Thomas

unread,
Nov 20, 2023, 10:00:38 PM11/20/23
to Google Visualization API
I thought I'd try using JavaScript's template strings to produce some charts, but cannot make them work. The idea was to pass a variable into the visualization chart code. The code I used was:

function newCharts(){
chartType=`BarChart`;
var chartStr = `google.visualization.${chartType}(document.getElementById('awstats-graph'))`;
console.log(chartStr);
newChart = new chartStr;
newChart.draw(drawData);
}

The console output looks OK and gives:

google.visualization.BarChart(document.getElementById('awstats-graph'))

But then I get the error:

Uncaught Error: Error handling Query strict JSON response: TypeError: chartStr is not a constructor

Does this mean there's something wrong with the code or that I cannot use this method?

I got what I wanted to do by using the drawchart method - https://developers.google.com/chart/interactive/docs/reference#drawchart

but am curious about the template strings.

The working code can be see at https://brisray.com/utils/awslogs/

Daniel LaLiberte

unread,
Nov 21, 2023, 12:38:28 PM11/21/23
to google-visua...@googlegroups.com
Hi Ray

Your chartStr is still a string, not an expression, even though it looks like an expression when you print it out.  At best, you would have to evaluate the string to turn it into code.

The drawChart function and ChartWrapper class do a lookup of the string name of a chartType in order to interpret the string as a chart type that can be executed.  Doing that may require dynamically loading more packages, if they are not already loaded.

--
You received this message because you are subscribed to the Google Groups "Google Visualization API" group.
To unsubscribe from this group and stop receiving emails from it, send an email to google-visualizati...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/google-visualization-api/d421ba86-9892-4c83-a635-dce9f99a47e3n%40googlegroups.com.


--

Daniel LaLiberte

 • SWE

 Cambridge MA

 • dlaliberte@Google.com

Ray Thomas

unread,
Nov 21, 2023, 2:40:25 PM11/21/23
to Google Visualization API
Thanks Daniel,

I guessed it was still a string  The drawchart method works just as well as anything and accepts practically anything in  its option list so I really was just exploring possibilities.

I also tried eval() and that returns the strict JSON response as well.

Ray

Reply all
Reply to author
Forward
0 new messages