如何从ES6类创建Google图表

时间:2018-07-12 17:55:50

标签: google-visualization es6-class

我不太确定如何进行以下工作。基本上,我想将所有Google图表逻辑封装在es6类中,我可以在要创建图表的任何地方调用它。但这不起作用,我不确定自己在做什么错。错误-无法读取未定义属性'dataArray'指向此行:

let row1 = this.dataArray[0];

这是代码。

<html>
<head>
    <title>test</title>
</head>
<body>
    <div id="chart"></div>

    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>

    <script type="text/javascript">
        class LineChartGenerator {

            constructor(dataArray, div, title) {
                this.dataArray = dataArray;
                this.div = div;
                this.title = title;
            }

            draw() {
                console.log(this.dataArray);
                google.charts.load('current', { 'packages': ['line'] });
                google.charts.setOnLoadCallback(this.drawChart);
            }


            drawChart() {
                var data = new google.visualization.DataTable();
                let row1 = this.dataArray[0];
                row1.foreach(item, function(){
                    data.addColumn('number', item);
                });

                data.addRows(this.dataArray.slice(1));

                var options = {
                    title: this.title
                };

                var chart = new google.visualization.LineChart(document.getElementById(this.div));

                chart.draw(data, options);
            }
        }


        var data = [
          ['Year', 'Sales', 'Expenses'],
          ['2004',  1000,      400],
          ['2005',  1170,      460],
          ['2006',  660,       1120],
          ['2007',  1030,      540]
        ];

        var l = new LineChartGenerator(data, "chart", "Test");
        l.draw();

    </script>
</body>
</html>

0 个答案:

没有答案