Further encapsulate Highchart to create your own chart plugin: Jhighchart.js

Source: Internet
Author: User

Highcharts is a library of diagrams written in plain JavaScript that makes it easy to add interactive diagrams to Web sites or Web applications. Supported chart types include graph, area, histogram, pie, scatter, and synthetic charts. But referring to an example of the official website, I found that if the highchart is used frequently in the project, it is quite complicated to follow it, and what I call complexity here is not difficult but troublesome, because every diagram you write you have to re-write JavaScript code similar to the following structure:

$ (' #container '). Highcharts ({title: {text: ' Monthly Average temperature ', x: -20//center            }, Subtitle: {text: ' Source:WorldClimate.com ', x: -20}, Xaxis: { Categories: [' Jan ', ' Feb ', ' Mar ', ' Apr ', ' may ', ' June ', ' Jul ', ' yaxi ', ' Sep ', ' Oct ', ' Nov ', ' Dec ']}, S: {title: {text: ' Temperature (°c) '}, plotlines: [{val ue:0, width:1, color: ' #808080 '}]}, tooltip: {Value Suffix: ' °c '}, Legend: {layout: ' vertical ', align: ' right ', verticalalign : ' Middle ', borderwidth:0}, series: [{name: ' Tokyo ', data: [7.0, 6.9, 9. 5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6]}, {name: ' New York ', data: [-0.2, 0 .8, 5.7, 11.3, 17.0, 22.0, 24.8, 24.1, 20.1, 14.1, 8.6, 2.5]}, {name: ' Berlin ', data: [-0.9, 0.6, 3.5, 8.4, 13.5, 1 7.0, 18.6, 17.9, 14.3, 9.0, 3.9, 1.0]}, {name: ' London ', data: [3.9, 4.2, 5.7, 8.5, 11.9, 1 5.2, 17.0, 16.6, 14.2, 10.3, 6.6, 4.8]});

So if the use of the project must be very cumbersome, it is necessary to highchart further encapsulation. The simple point of encapsulation is to find common points. Look at a few highchart of the chart source will find that they are just a few: title (title, SubTitle), x-axis (Xaxis), y-axis (YAxis), Legend (legend), Data point Options (plotoptions), Data item (series), so we only need to process these elements. First look at the results of my package:

var JHC = new $.jhighchart ({                Renderto: $ ("#numberCardChart"),                chart:{chartbgcolor: "#FBFCFD"},                ChartType : "column",                title: "Merchant Member statistics",                subtitle: "2014-2015 member statistics",                xaxisname: "Time",                xcategories: Responsedata.categories,                yaxissetting: [{key: "Numbers", Name: "Number of members", Oppositeoption:false}],                yaxiscolumn: [{ Key: "Numbers", Name: "Number of members"}],                series:responseData.series,                legend:{"enabled": false},                click:function (params) {                    querynumberdetail (params);                }        });    Jhc.create ();

Renderto for the displayed Div Id,chart for the chart setting, the display type of the ChartType chart, title main title, subtitle subtitle, xaxisname x axis name, Xcategoriesx axis data, yaxissetting Y-Axis settings, series data items.

The configuration option for the entire highchart is as follows:

var options = $.extend ({//Background color chart:{chartbgcolor: ' #FFFFFF ', Width: ", Height:"},//Required Location of the display (within which DOM element) Renderto: $ (document.body),//Chart type: Bar,line,spline,column,pie,area,areaspline,co              Mbine,bubble,scatter chartType: "",//Chart big title title: "",//Chart subheadings Subtitle: ",//x axis name xaxisname:" ",//x axis list data, is a JSON list object XCat egories:{},//y axis settings, can add multiple y-axes, key-y axis name, Oppositeoption-true/false (true right, false to left) Yaxissett               ing: [{key: "", Name: "", Oppositeoption:false}],//key-y axis corresponding data, nane-name, charttype-graph type, yindex-each indicator set needs a specific y-axis index               Yaxiscolumn: [{key: "", Name: "", ChartType: "", yindex:0, Color:null}],//Chart data source, is a JSON list object Series: {},//point MouseOver event mouseover:function () {},//point m Ouseout Event MOuseout:function () {},//point Click event: Set down Drill Method Click:function () {},//Whether the export button is turned on              Exportbutton:true,//Icon container size Containersize:{width:null,height:null}, Legend options: Default does not show: specific configuration See API Legend:{enabled:false,layout: "", Align: "", VerticalAlign: "", Floating:false,x: "", Y: "", b Ackgroundcolor: "#FFFFFF"},//Data point options//showinlegend: whether to show pie chart example, dataenable: whether to show pie data points PLO Toptions:{showinlegend:false,dataenable:false},//Basic parameter settings: Mainly used to set the chart height, width chart:{width: "", Height: "" }}, setting);

Above is the JavaScript part to be processed, encapsulated. But when our data comes through the background, how can we encapsulate the background data into the plugin? Perhaps cautious Bo friend found, in the above use method notice these two places: XCategories:responseData.categories, Series:responseData.series, ResponseData is the return data for the background, the categories is the x-axis data, and the series is the data item. In the background I dealt with this:


The above UML is to implement the background data structure diagram, wherein Buildchartsservice is the top level abstract class, outward exposing the buildcharts method, the realization chart subclass needs to implement Createxaxiscategories, Createseries two methods. Chartbaseaction is the base action for building charts, and through AJAX requests, its main function is to provide basic statistical data valuestack and encapsulate the data items. Serieschartvo, SERIESDATASVO Two classes are support classes for chart statistics items, where serieschartvo is the statistical chart data option Vo, and a serieschartvo corresponds to a record, The Jhightchart internal implementation uses the Yaxiscolumn key with the Serieschartvo Kye for one by one correspondence. SERIESDATASVO is the statistical chart number, the statistical internal data representation is: Data:[{name: ", y:", drilldown: ", Params:"} ", the class is mainly the user data item construction and configuration, such as the configuration of drill data parameters and so on.

Instance

Request Action Inheritance Build chart chartbaseaction:

public class Querydailystatisticsinfoaction extends chartbaseaction{    private static final long Serialversionuid = 6822826781517049491L;        @Resource    private Ihistorystatisticsdailytransservice historystatisticsdailytransservice;    @SuppressWarnings ("unchecked")    @Override public    String execute () throws Exception {        list<json> List = (list<json>) getrequest (). GetSession (). getattribute ("Dailylist");                Valuestack = Historystatisticsdailytransservice.getdailystatisticsinfo (list);                Getrequest (). GetSession (). RemoveAttribute ("Dailylist");                return SUCCESS;}    }

Private map<string, object> builddailystatisticsinfo (list<string> categories,            list<json> List ) throws serviceexception{        map<string, object> categoriesmap = new hashmap<string, object> ();        Categoriesmap.put ("list", categories);                map<string, object> seriesmap = new hashmap<string, object> ();        Seriesmap.put ("serieslist", list);                map<string, object> contentmap = new hashmap<string, object> ();        X-axis data item        contentmap.put ("categories", Categoriesmap);        Data item        contentmap.put ("series", Seriesmap);                Buildchartsservice service = new Dailystatisticsinfochart ();        Return Service.buildcharts (CONTENTMAP);    }

Finally, use Dailystatisticsinfochart's Buildchart method to construct the chart data

public class Dailystatisticsinfochart extends buildchartsservice{@SuppressWarnings ("unchecked") protected list<s Tring> createxaxiscategories (map<string,object> xaxismap) {list<string> categories = (List<Strin        g>) xaxismap.get ("list");    return categories; } @Override @SuppressWarnings ("unchecked") protected list<serieschartvo> createseries (map<string,object& Gt Contentmap) throws Serviceexception {list<json> jsons = (list<json>) contentmap.get ("series                List ");        list<seriesdatasvo> dataList = new arraylist<seriesdatasvo> ();        SERIESDATASVO datas = null;            for (int i = 0; i < jsons.size (); i++) {Jsonobject json = Jsonobject.fromobject (Jsons.get (i));            String name = (string) json.get ("PayType");                        Object y = json.get ("Amt");            Datas = new SERIESDATASVO (name, y);        Datalist.add (datas);       }         Serieschartvo chartvo = new Serieschartvo ("Dailystatistics", dataList);        list<serieschartvo> chartlist = new arraylist<serieschartvo> ();                Chartlist.add (CHARTVO);    return chartlist; }}

After the data is built, the final step is to use Jhighchart to implement the chart:

JHC = new $.jhighchart ({                Renderto: $ ("#chartDIV"),                chartType: "Pie",                title: "Merchant Day Settlement Statistics",                xaxisname: "",                xCategories:responseData.categories,                yaxissetting: [{key: "Dailystatistics", Name: "Turnover", Oppositeoption: False}],                yaxiscolumn: [{key: "Dailystatistics", Name: "Total"}],                series:responseData.series,                legend:{" Enabled ": false},                plotoptions:{" dataenable ": true},                click:function (params) {                    querydetail (params);                }        });    Jhc.create ();

Demo download

Chart.rar

Further encapsulate Highchart to create your own chart plugin: Jhighchart.js

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.