我正在尝试将google可视化图表集成到我的backbone.js应用程序中.目前,我在ChartView类的render函数中同时具有google.load(可视化)和setOnLoadCallback(drawVisualization)调用.谷歌可视化库似乎正在加载正确,但回调永远不会执行.
下面是一个显示问题的例子,如果有人可以帮助我会非常感激!
<!doctype html> <html> <head> <title>App</title> <Meta charset="utf-8"> </head> <body> <div id="content"></div> <script src="lib/jquery-1.7.2.min.js"></script> <script src="lib/underscore.js"></script> <script src="lib/backbone.js"></script> <script src="http://www.google.com/jsapi"></script> <script> ChartView = Backbone.View.extend({ render:function () { $(this.el).html('<p>gviz line chart:</p>' + '<div id="gviz" style="width:600px; height:300px;"></div>'); google.load('visualization','1',{packages:'linechart'}); google.setOnLoadCallback(this.drawVisualization); return this; },//This never gets called drawVisualization:function () { console.log("In draw visualization"); var data = this.createDataTable('date'); var chart = new google.visualization.LineChart(this.$('#gviz')); chart.draw(data,null,null); },createDataTable:function (dateType) { console.log("Creating datatable"); var data = new google.visualization.DataTable(); data.addColumn(dateType,'Date'); data.addColumn('number','Column A'); data.addColumn('number','Column B'); data.addRows(4); data.setCell(0,new Date("2009/07/01")); data.setCell(0,1,1); data.setCell(0,2,7); data.setCell(1,new Date("2009/07/08")); data.setCell(1,2); data.setCell(1,4); console.log("Created datatable " + data.toJSON()); return data; } }); var AppRouter = Backbone.Router.extend({ routes:{ "":"chart" },chart:function () { console.log("Showing chart"); $("#content").append(new ChartView().render().el); } }); router = new AppRouter(); Backbone.history.start(); </script> </body> </html>
解决方法
好吧,在另一个月之前为后代录制这个.可以将回调设置为google.load调用本身的arg,而不是使用google.setOnLoadCallback方法.还必须调整代码以获取jquery对象的第一个子代,它工作正常.
ChartView = Backbone.View.extend({ render:function () { $(this.el).html('<p>gviz line chart:</p>' + '<div id="gviz" style="width:600px; height:300px;"></div>'); google.load('visualization',{'callback':this.drawVisualization,'packages':['linechart']}); return this; },drawVisualization:function () { console.log("In draw visualization"); var data = new google.visualization.DataTable(); data.addColumn('date','Date'); data.addColumn('number','Column A'); data.addColumn('number','Column B'); data.addRows(4); data.setCell(0,new Date("2009/07/01")); data.setCell(0,1); data.setCell(0,7); data.setCell(1,new Date("2009/07/08")); data.setCell(1,2); data.setCell(1,4); var chart = new google.visualization.LineChart(this.$('#gviz').get(0)); chart.draw(data,null); } });