我想从页面中获取Google Chart数据,将其转换为CSV,然后将其移交给下载程序。
在chartpage.js
function downloadCSV(args) {
var csvData, filename, link;
var action = args.action_name;
var csv = convertArrayOfObjectsToCSV({
action_name: action
});
filename = args.filename || 'export.csv';
csvData = encodeURI(csv);
link = document.createElement('a');
link.setAttribute('href', 'data:text/csv;charset=utf-8,' + csvData);
link.setAttribute('type', 'data:text/csv;charset=utf-8');
link.setAttribute('download', filename);
link.click();
}
然后在chart.coffee中:
init_chart = ->
chart = new google.visualization.BarChart(document.getElementById('chart_div')); //#chart_div in chart.html.haml
render_chart = (items, year)->
@data = new google.visualization.DataTable()
data.addColumn 'string', I18n.t('charts.name')
// Other logic for building chart from Rails DB Data
for key_item in items
label = []
[key, item] = key_item.split(':')
if key == 'competitor_meded_involvement'
label.push I18n.t('charts.competitor')
label.push I18n.t("kol_items.#{item}")
data.addColumn 'number', label.join(' - ')
// and so on.
google.charts.load 'current', 'packages': ['corechart']
google.visualization.events.addListener(@data, 'ready', setData) // I read this was a solution but it doesn't seem to help
google.charts.setOnLoadCallback ->
init_chart()
render_chart()
$(setData(@data)) //I tried passing this to a setter method over in chartpage.js which takes @data and tries to set it globally but that makes no difference at page load time.
在chart.html.haml中:
%h5{id: "downloadCSV"}= link_to '<i class="fa fa-file-excel-o"></i> Download CSV'.html_safe, "#"
#chart_div
所以我在主JS中尝试了上面和下面的内容:
case 'chart_kol_comparison':
google.setOnLoadCallback(function() {
str = google.visualization.dataTableToCsv(window.data); //This builds the CSV string and returns it to the download JS for output
});
但是来自页面JS(HAML)的数据变量:
@data = new google.visualization.DataTable()
似乎只在页面加载后才可用 - 而不是上面的JS加载并尝试获取数据时。
当我在控制台中运行以下内容时,它会起作用,但在页面加载时则不行。这是在Rails应用程序中。
str = google.visualization.dataTableToCsv(data); //var data is populated after page loads (available from console) but not from the JS at page load time.
我该如何解决这个问题?
答案 0 :(得分:2)
这里似乎发生的事情是你在调用draw之后不等待图表/数据表完全呈现。因此,实现此目的的最佳方法是创建一个等待图表/数据表的ready事件的事件处理程序。
google.visualization.events.addListener(tableChart, 'ready', myReadyHandler);
并添加填充变量的函数,但在图表/数据表准备好之后。
function myReadyHandler(){
// fill variables here or call directly your other methods,
// this will ensure, you can grab data from the chart/datatable
// because is completely rendered and you can play with that
}
答案 1 :(得分:0)
对我来说,事件绑定从未起作用。所以我必须做的是,在图表page.js:
function setData(data) {
after_data = data;
}
google.visualization.dataTableToCsv(window.after_data);
在chart.coffee中:
setData(data)
数据是Google dataTable对象。
所以基本上我必须在页面的google js文件之外创建一个setter。