谷歌图表不会重新绘制循环中的新值

时间:2015-04-06 19:55:25

标签: javascript charts google-visualization

我正在尝试使用Google图表API和javascript创建更新的实时图表,但我似乎无法让图表更新。我得到了绘制图表,但是当我的更新数据脚本再次运行时,它会调用该函数再次绘制谷歌图表,因为它从我的自定义库中接收了新数据。

<!DOCTYPE HTML>
<html>
    <head>
        <title>TheWayWardJourney</title>
        <script src="cynergi.js"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
        <script type="text/javascript" src="https://www.google.com/jsapi"></script>
        <script>
            function updateData(){
                // this is retrieving rows from the db and looping through them.
                var data = Cynergi.get('http://:3000/computer_stats?order=time.asc');
                var data_array = []
                $.each( data, function( i, item ) {

                    html_insert = 'Computer Name:' + item.computer_name + '<br>Operating System:' + item.operating_system + '<br>CPU Model: ' + item.cpu_model + '<br>Cores Assigned: ' + item.cores + '<br>CPU MHz: ' + item.cpu_mhz + '<br>CPU Cache: ' + item.cpu_cache + '<br>Net Devices: ' + item.net_devices + '<br>Devices: ' + item.devices;

                    stats = 'Total Memory: ' + item.total_memory + '<br>Free Memory:' + item.free_memory  + '<br> Active Memory:' + item.active_memory + '<br> Bounce Memory:' + item.bounce_memory + '<br> Buffered Memory:' + item.buffers_memory + '<br> Locked Memory:' + item.locked_memory + '<br> Swap Memory:' + item.swap_memory + '<br> Swap Free:' + item.swapfree_memory
                        var time = new Date(parseInt(item.time))
                        data_array.push([{v: time.toString()}, {v: parseInt(item.cpu_usage)}]);
                });
                    drawCharts(data_array);
                    $( "#computer_info" ).html(html_insert);
                    $( "#computer_stats" ).html(stats);
                    setTimeout(function(){  updateData(); }, 30000);
            }
            updateData();
            function update_messages(){
                var message_data = Cynergi.get('http://:3000/page_contact?order=time.asc');
                var message_insert = '';
                $.each( message_data, function( i, item ) {
                    var time = new Date(parseInt(item.time))
                    message_insert = message_insert + '<p>From: ' +item.name+ '</p><p>Message: ' + item.message + '</p><p>Email: ' + item.email + '</p><p>Time: ' + time + '</p><button onclick="delete_post(' + item.id + ')">Delete</button>'

                });
                    $( "#messages" ).html(message_insert);
                    setTimeout(function(){  update_messages(); }, 1000);
            }
            update_messages();
            //this is how you insert into the db
            var d = new Date();
            var time = d.getTime();
            var post = {"name":"Grant Zukel","email":"Test Email","message":"Test Message","read":"no","username":"zukeru","time":time};
            var json_data = post;
            Cynergi.insert('http://:3000/page_contact', json_data);
            //this is how you delete from the db
            function delete_post(id){
                if (confirm('Are you sure you want to delete this post?')) {                      Cynergi.delete('http://m:3000/page_contact?id=eq.' + id);
                }
            }
            //this is how you do an update to teh db
            var d = new Date();
            var time = d.getTime();
            var post = {"name":"Grant Zukel","email":"Test Email@fuckaroasdasd","message":"Test Message UPDATED","read":"no","username":"zukeruasdasd","time":time};
            var json_data = post;
            Cynergi.update('http://:3000/page_contact?id=eq.26', json_data);
            $( document ).ready(function() {
                $( "#computer_info" ).html(html_insert);
                $( "#computer_stats" ).html(stats);
                $( "#sentStatus" ).html(sentStatus);
                $( "#deleteStatus" ).html(deleteStatus);
                $( "#updateStatus" ).html(updateStatus);
                $( "#messages" ).html(message_insert);
            });
            function drawCharts(data_array){
                google.load('visualization', '1.1', {packages: ['line']});
                google.setOnLoadCallback(drawChart);
                function drawChart() {
                      var data = new google.visualization.DataTable();
                      data.addColumn('string', 'Time');
                      data.addColumn('number', 'CPU Usage');
                      data.addRows(data_array);
                      var options = {
                        chart: {
                          title: "Playground's %% CPU Usage",
                          subtitle: 'you know you likie.'
                        },
                        width: 900,
                        height: 500
                  };
                  var chart = new google.charts.Line(document.getElementById('chart'));
                  console.log(chart);
                  chart.draw(data, options);
                }
            }
    </script>
    </head>
    <body>
        <div id="chart"></div>
        <p style='text-align:left;align:left;' id='updateStatus'></p></p>
        <p style='text-align:left;align:left;' id='sentStatus'></p></p>
        <p style='text-align:left;align:left;' id='deleteStatus'></p></p>
        <p style='text-align:left;align:left;' id='computer_info'></p></p>
        <p style='text-align:left;align:left;' id='computer_stats'></p></p>
        <p style='text-align:left;align:left;' id='messages'></p></p>
    </body>
</html>

1 个答案:

答案 0 :(得分:0)

不完全确定你的要求。我想让图表更新,但我不清楚你不喜欢当前的行为。您的updateData函数显式调用drawCharts,但我得到的印象是您不希望它。

乍一看,看起来drawCharts每次都会调用drawChart,这会导致整个图表被重新创建(而不是仅仅刷新数据。)但是,我认为on load回调只会执行一次,在这种情况下,没有引起任何更新。这似乎是由this验证的。

基于此我假设问题不是多次调用drawCharts强制完全重做所有内容,并且问题是当它被多次调用时,它不是&#39;重新绘制图表。

要解决这个问题,我会将drawCharts改为两个函数:

var chartLibraryIsLoaded = false;


function drawCharts(data_array) {
    function drawChart() {
        var data = new google.visualization.DataTable();
        data.addColumn('string', 'Time');
        data.addColumn('number', 'CPU Usage');
        data.addRows(data_array);
        var options = {
            chart: {
                title: "Playground's %% CPU Usage",
                subtitle: 'you know you likie.'
            },
            width: 900,
            height: 500
        };
        var chart = new google.charts.Line(document.getElementById('chart'));
        console.log(chart);
        chart.draw(data, options);
    }

    if (chartLibraryIsLoaded) {
        drawCharts();
    } else {
        google.load('visualization', '1.1', {
            packages: ['line']
        });
        google.setOnLoadCallback(function() {
            chartLibraryIsLoaded = true;
            drawCharts();
        });
    }
}

我不喜欢这种方法,但我希望尽可能做出最小的改变。我个人会重做这个,不使用全局变量,避免重新定义drawChart。

即使它不是您要求的,我也会考虑重构这一点,以避免重新创建DataTable和图表,而是操纵DataTable中的数据并重新绘制图表。