prevent default sort event in google chart table

2019-07-22 04:29发布

问题:

Is it possible to prevent default sort event from being fired in a google chart table object? If we take the example from code playground how could this be tweaked so as to e.g. prevent sorting from happening when clicking on "age" header?

i.e. doing nothing to the table chart (My idea is to have default sorting in all headers except in one, where another clicking event (managed by an event listener in an external js would fire) would be fired but without firing the sort event (and thus without appearing the little sorting arrow))

For example, the following doesn't work (it still calls the default sort method):

function drawVisualization() {
var table = new google.visualization.Table(document.getElementById('table'));
table.draw(sortData, null);

var chart = new google.visualization.BarChart(document.getElementById('chart'));
chart.draw(sortData, null);

google.visualization.events.addListener(table, 'sort',
  function(event) {
    if(event.column != 1){
      sortData.sort([{column: event.column, desc: !event.ascending}]);
      chart.draw(sortData, null);
    }
  }
);
}

Thank you for any pointers

回答1:

Set the Table's sort option to event. This disables the default sorting and makes the chart throw a "sort" event when the headers are clicked. If you want to track sorting properly, you need to redraw the chart with the sortColumn and sortAscending options set:

var options = {
    sort: 'event'
};
google.visualization.events.addListener(table, 'sort', function(event) {
    if(event.column != 1) {
        options.sortColumn = event.column;
        options.sortAscending = event.ascending;
        sortData.sort([{column: event.column, desc: !event.ascending}]);
        table.draw(sortData, options);
    }
});

[edit - full code for function to use custom sorting for table, based on playground code]

function drawVisualization() {
    var options = {
        sort: 'event'
    };
    var table = new google.visualization.Table(document.getElementById('table'));
    table.draw(sortData, options);

    var chart = new google.visualization.BarChart(document.getElementById('chart'));
    chart.draw(sortData, null);

    google.visualization.events.addListener(table, 'sort', function(event) {
        if(event.column != 1) {
            options.sortColumn = event.column;
            options.sortAscending = event.ascending;
            sortData.sort([{column: event.column, desc: !event.ascending}]);
            table.draw(sortData, options);
        }
    });
}