JS文件的小调整:循环前初始化

时间:2018-08-27 10:23:49

标签: javascript google-visualization

我下载了一个小的代码段,当用户单击图例时,它可以过滤Google图表系列。

基本上,我有生成图形的代码,然后有一个事件侦听器,该事件侦听器根据用户的点击隐藏/显示序列。

我想做的是要么触发代码中的事件,要么遍历整个系列以根据参数隐藏其中的一些。

这是我的代码:

function get_performances_graph_data(){
    $values = $kpis_array = array();
    $kpis = get_kpi_array();
    global $wpdb;

    $i = 0;
    foreach( $kpis as $k ){
        if( !isset( $k['hidden'] ) ){
            $h = $k['header'];
            $format = 'number';
            if( isset( $k['format'] ) )
                $format = $k['format'];
            $temp = array(  'label' => $h , 'slug' => toUri( $h ) , 'id' => $i , 'format' => $format );
            $kpis_array[] = $temp;
            $i++;
        }
    }

    $req = "SELECT * FROM " . gq_prefix() . "performances ORDER BY date ASC";
    // debug_var( $req );
    $performances = $wpdb->get_results( $req );
    $prev_val = array();
    foreach( $performances as $p ){
        // debug_var( $p );
        foreach( $kpis as $k ){
            if( !isset( $k['hidden'] ) ){
                $slug = toUri( $k['header'] );
                $val = '';
                if( isset( $p->$slug ) )
                    $val = $p->$slug;
                if( isset( $k['format'] ) && $k['format'] == 'date' ){
                    $date_str = explode( ";" , str_replace( '-' , ';' , $val ) );
                    $y = $date_str[0];
                    $m = $date_str[1] - 1;
                    $d = $date_str[2];
                    $row[$slug] = "new Date($y, $m, $d)";
                }
                else{
                    if( empty( $val ) ){
                        if( isset( $prev_val[$slug] ) )
                            $val = $prev_val[$slug];
                    }
                    else
                        $prev_val[$slug] = $val;
                    $row[$slug] = $val;
                }
                // debug_var( $val , $slug );
            }
        }
        $values[] = $row;
    }

    // debug_var( $values );
    return array( 'values' => $values , 'kpis' => $kpis_array );
}
function get_ticks( $dataset ){
    // debug_var( $dataset );
    $first = reset( $dataset )['date'];
    $last = end( $dataset )['date'];
    $dates = array( $first );

    // debug_var( $last , $first );

    $f_s = explode( ';' , str_replace( 'new Date(' , '' , str_replace( ')' , '' ,  str_replace( ', ' , ';' , $first ) ) ) );
    $y = $f_s[0];
    $m = $f_s[1];
    // $d = $f_s[2];
    // debug_var( $f_s );
    $l_s = explode( ';' , str_replace( 'new Date(' , '' , str_replace( ')' , '' ,  str_replace( ', ' , ';' , $last ) ) ) );
    $y_l = $l_s[0];
    $m_l = $l_s[1];
    // $d = $l_s[2];
    // debug_var( $l_s );

    $out = false;
    while( !$out ){
        if( $m >= 6 ){
            // debug_var( $m , 1 );
            $m = 0;
            // debug_var( $m , 11 );
            $y++;
        }
        else{
            // debug_var( $m , 2  );
            $m = 6;
        }
        // debug_var( $y , $y_l );
        // debug_var( $m , $m_l );
        if( $y > $y_l || ( $y == $y_l && $m > $m_l ) )
            $out = true;
        else
            $dates[] = "$y,0$m,01";

    }
    $dates[] = $last;

    $output = '[';
    foreach( $dates as $d ){
        $output .= "new Date($d), "; // 2014,3,15
    }
    $output = rtrim( $output , ', ' );
    $output .= ']';

    return $output ;
}
function display_graph( $atts ){
    $dataset = array( 'all' );
    if( isset( $atts['dataset'] ) )
        $dataset = $atts['dataset']; // string

    $dataset = array( 'date' , 'cac-40' , 'marches-actions' , 'fonds-en-euros' );

    $output = '';

    // $graph_type = 'ScatterChart';
    $graph_type = 'LineChart';
    $data = get_performances_graph_data();
    // debug_var( $data );

    $data_values = $data['values']; // Contains the dataset
    $data_kpis = $data['kpis']; // Contains each KPI's ID

    $ticks_string = get_ticks( $data_values );

    $options = "
            chartArea: {
                width: '90%'
            },
            // pointSize: 1,
            legend:{
                maxLines: 3,
                position: 'top',
                textStyle: {
                    fontSize: 15
                }
            },
            hAxis: {
                fontSize: 10,
                format: 'MMM y',
                gridlines: {
                    color: '#eaeaea',
                    count: 15
                },
                ticks: $ticks_string,
            },
            crosshair: {
                trigger: 'selection',
                orientation: 'vertical',
                color: '#143278',
            }
    ";

    $output .= '<div id="chart_div"></div>';
    $output .= '
    <script type="text/javascript" src="https://www.google.com/jsapi?autoload={\'modules\':[{\'name\':\'visualization\',\'version\':\'1.1\',\'packages\':[\'corechart\']}]}"></script>

    <script>
      google.load("visualization", "1", {packages:["corechart"]});
      google.setOnLoadCallback(drawChart);
      function drawChart() {
        var data = new google.visualization.DataTable();' . "\n";

    foreach( $data_kpis as $d ){
        $output .= "data.addColumn('" . $d['format'] . "', '" . $d['label'] . "');\n";
    }

    // $rows = "\ndata.addRows([\n";
    $rows = '';
    foreach( $data_values as $d ){
        // $row = "[";
        $row = "\ndata.addRow([";
        foreach( $data_kpis as $k ){
            $slug = $k['slug'];
            $val = $d[$slug];
            // debug_var( $val );
            if( isset( $k['format'] ) && $k['format'] == 'date' ){
                $row .= "$val,\n";
            }
            else{
                if( !isset( $val ) )
                    $val = "''";
                $row .= "// $slug\n$val, \n";
                // $row .= "$val,\n";
            }
        }
        // $rows .= rtrim( rtrim( $row , ',') , ",\n") . "],\n";
        $rows .= rtrim( rtrim( $row , ',') , ",\n") . "]);\n";
    }
    // $output .= rtrim( rtrim( $rows , ',') , ",\n") . "]);\n";
    $output .= rtrim( rtrim( $rows , ',') , ",\n") . "\n";
    $output .= '

        var options = {' . $options . '};
        var chart = new google.visualization.' . $graph_type . '(document.getElementById(\'chart_div\'));
        chart.draw(data, options);

        var columns = [];
        var series = {};
        for (var i = 0; i < data.getNumberOfColumns(); i++) {
            // HERE, I need to select which column is in $dataset (if $dataset != array("all")) and hide the rest
            columns.push(i);
            if (i > 0) {
                series[i - 1] = {};
            }
        }

        console.dir(series);
        console.dir(columns);

        var options = {
            series: series,
            ' . $options . '
        }

        var view = new google.visualization.DataView(data);
        view.setColumns(columns);
        chart.draw(view, options);

        google.visualization.events.addListener(chart, \'select\', function () {
            var sel = chart.getSelection();
            // if selection length is 0, we deselected an element
            if (sel.length > 0) {
                // if row is undefined, we clicked on the legend
                if (sel[0].row === null) {
                    var col = sel[0].column;
                    if (columns[col] == col) {
                        // hide the data series
                        columns[col] = {
                            label: data.getColumnLabel(col),
                            type: data.getColumnType(col),
                            calc: function () {
                                return null;
                            }
                        };

                        // grey out the legend entry
                        series[col - 1].color = \'#CCCCCC\';
                    }
                    else {
                        // show the data series
                        columns[col] = col;
                        series[col - 1].color = null;
                    }
                    var view = new google.visualization.DataView(data);
                    view.setColumns(columns);
                    chart.draw(view, options);

                    console.log( series );
                    console.log( columns );

                }
            }
        });

      }</script>
    ';

    return $output;
}

我的函数正在解析一个名为$ dataset的数组。默认值为“全部”,但是我添加了一小段代码以测试将来可能会解析的模式。

$dataset = array( 'date' , 'cac-40' , 'marches-actions' , 'fonds-en-euros' );

正如您在我的代码中看到的那样,有时我会得到一系列的序列和列:

var columns = [];
        var series = {};
        for (var i = 0; i < data.getNumberOfColumns(); i++) {
            // HERE, I need to select which column is in $dataset (if $dataset != array("all")) and hide the rest
            columns.push(i);
            if (i > 0) {
                series[i - 1] = {};
            }
        }

        console.dir(series);
        console.dir(columns);

在脚本末尾,我有一个循环,可在单击事件时隐藏/显示列:

google.visualization.events.addListener(chart, \'select\', function () {
            var sel = chart.getSelection();
            // if selection length is 0, we deselected an element
            if (sel.length > 0) {
                // if row is undefined, we clicked on the legend
                if (sel[0].row === null) {
                    var col = sel[0].column;
                    if (columns[col] == col) {
                        // hide the data series
                        columns[col] = {
                            label: data.getColumnLabel(col),
                            type: data.getColumnType(col),
                            calc: function () {
                                return null;
                            }
                        };

                        // grey out the legend entry
                        series[col - 1].color = \'#CCCCCC\';
                    }
                    else {
                        // show the data series
                        columns[col] = col;
                        series[col - 1].color = null;
                    }
                    var view = new google.visualization.DataView(data);
                    view.setColumns(columns);
                    chart.draw(view, options);

                    console.log( series );
                    console.log( columns );

                }
            }
        });

这是我迷路的部分。

我当时在想,当我得到第一组系列和列时,我可以通过在它们之间循环并检查&atts ['dataset']参数或通过使用索引直接更改它们来隐藏其中的一部分。 / p>

非常感谢您的帮助和时间!

格雷格

0 个答案:

没有答案