Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
362 views
in Technique[技术] by (71.8m points)

highstock - Manage multiple highchart charts in a single webpage

I am having multiple highchart charts of various types(Bar,Pie, Scatter type) in a single web page. Currently I am creating config object for each graph like,

{
chart : {},
blah blah,
}

And feeding them to a custom function which will just call HighCharts.chart(). But this results in duplication of code. I want to manage all this chart rendering logic centrally.

Any Idea on how to do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use jQuery.extend() and Highcharts.setOptions.
So first you'll make the first object which will be extended by all your charts, this object will contain your Highchart default functions.

You can do it using namespacing.
The following way is good when you have very different charts.

Default graphic:

var defaultChart = {
    chartContent: null,
    highchart: null,
    defaults: {

        chart: {
            alignTicks: false,
            borderColor: '#656565',
            borderWidth: 1,
            zoomType: 'x',
            height: 400,
            width: 800
        },

        series: []

    },

    // here you'll merge the defauls with the object options

    init: function(options) {

        this.highchart= jQuery.extend({}, this.defaults, options);
        this.highchart.chart.renderTo = this.chartContent;
    },

    create: function() {

        new Highcharts.Chart(this.highchart);
    }

};

Now, if you want to make a column chart, you'll extend defaultChart

var columnChart = {

    chartContent: '#yourChartContent',
    options: {

        // your chart options
    }

};

columnChart = jQuery.extend(true, {}, defaultChart, columnChart);

// now columnChart has all defaultChart functions

// now you'll init the object with your chart options

columnChart.init(columnChart.options);

// when you want to create the chart you just call

columnChart.create();

If you have similar charts use Highcharts.setOptions which will apply the options for all created charts after this.

// `options` will be used by all charts
Highcharts.setOptions(options);

// only data options
var chart1 = Highcharts.Chart({
    chart: {
        renderTo: 'container1'
    },
    series: []
});

var chart2 = Highcharts.Chart({
    chart: {
        renderTo: 'container2'
    },
    series: []
});

Reference

COMPLETE DEMO


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...