Highcharts event handler after finishing redraw

Viewed 1499

I am trying to show the total of the Y axis as a subtitle for a HighStock chart. This is initially accomplished by summing up the point.y value of all the series, inside the "load" event like so:

chart: {
    events: {
        load: function () {
            var chart = this,
                series = chart.series,
                seriesSum = 0;
            series.forEach(function (series) {
                series.data.forEach(function (point) {
                    seriesSum += point.y
                })
            })
            this.update({
                subtitle: { text: 'TOTAL:  ' + seriesSum }
            });
        },
    }
}

Now I need to update the TOTAL amount after the chart has been redrawn after changing the timeframe using either the Navigator or the Range Selector. I know there is a "redraw" event, but that will end me up in an infinite loop. Which event should I be tack onto?

2 Answers

You can use the redraw event, and just not redraw within a pending redraw. For example:

chart: {
    events: {
        redraw: function () {
            this.update({
                subtitle: { text: 'TOTAL:  ' + seriesSum }
            }, false);
        }
    }
}

Note the false parameter to the Chart.update function to prevent further redrawing (infinite loop).

See this JSFiddle demonstration using Highcharts and the redraw event.

You can use update method with redraw flag in redraw event, but you must set right conditions to not to fall into an infinite loop:

var redrawEnabled = true;

var chart = Highcharts.chart('container', {
    chart: {
        zoomType: 'x',
        events: {
            redraw: function() {
                if (redrawEnabled) {
                    var sum = 0;
                    redrawEnabled = false;

                    Highcharts.each(this.series[0].points, function(point) {
                        if (point.isInside) {
                            sum += point.y;
                        }
                    });

                    this.update({
                        subtitle: {
                            text: sum
                        }
                    });

                    redrawEnabled = true;
                }
            }
        }
    },
    series: [{
        data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
    }]
});

Live demo: http://jsfiddle.net/BlackLabel/dewumkz6/

Related