L4zl0w
L4zl0w

Reputation: 1097

Update chart data in Dojo

I have the below function which reads JSON data and puts it on a chart. I would like to automatically update the chart data every say 10 seconds.

I have looked at dojo/timing and chart.updateSeries and I believe the combination of the two would do the trick but I'm not sure how I can implement this. Any help would be greatly appreciated.

function(xhr, json, arrayUtil, number, Chart, theme) {

            var def = xhr.get({
                url: "cpuusage.json",
                handleAs: "json"
            });

            def.then(function(res){
                var chartData = [];                 
                arrayUtil.forEach(res.chart, function(chart){
                    chartData[chart.x] = number.parse(chart.y);
                });

                //Draw chart
                var chart = new Chart("chartNode2");
                chart.setTheme(theme);
                chart.addPlot("default", {
                    type: "Columns",
                    markers: true,
                    gap: 5
                });
                chart.addAxis("x");
                chart.addAxis("y", { vertical: true, fixLower: "major", fixUpper: "major" });
                chart.addSeries("Monthly Sales",chartData);
                chart.render();

            }, function(err){
                console.error("Failed to load JSON data");
            });
        }

Upvotes: 0

Views: 1227

Answers (1)

Eugene Lazutkin
Eugene Lazutkin

Reputation: 43956

Try something like that:

var interval = setInterval(function(){
    // let's get new data
    xhr.get({
        url: "cpuusage.json",
        handleAs: "json"
    }).then(function(res){
        // data prep step - just like before
        var chartData = [];
        arrayUtil.forEach(res.chart, function(chart){
            chartData[chart.x] = number.parse(chart.y);
        });
        // update chart (it was created before)
        chart.updateSeries("Monthly Sales", chartData);
        chart.render();
    }, function(err){
        console.error("Failed to load updated JSON data");
    });
}, 10000); // 10s
...
// when we want to cancel updates
clearInterval(interval);

Sorry, I didn't use dojo/timing, I don't see much reason for it here, and prefer simple ways to do simple things.

Upvotes: 2

Related Questions