Reputation: 1934
I am having a bit of an issue with the Google Visualization library. I have a very simple table being built on the screen, and I need to disable sorting, but only for a certain column. I have gone through their documentation and found that you can define your own functions for events that will override the default, but it is not working. Here is an extremely simple example...
var chart = new google.visualization.Table(document.getElementById('myTable'));
google.visualization.events.addListener(chart, 'sort', function(e) { handleSort(e, chart); });
chart.draw(opts, dataTable);
function handleSort(e, chart) {
console.log('inside sort');
return false;
}
when I click on the column header I get the console log of 'inside sort', but the table will sort on that column. I have even tried...
function handleSort(e, chart) {
if(e.column == 9) {
chart.options['sortColumn'] = 0;
chart.options['isAscending'] = true;
}
}
When clicking the column header for column 9 it still sorts on column 9. I can't get it to stop sorting on that column. Essentially I have a button in the header for column 9, when the user clicks the button the page does something, but since it sorts the table, it ruins what is supposed to be happening. Also, inside the opts object that gets passed to the draw method, I do have 'sort' set to 'event' like they say in their documentation, but it will not work. The function gets run, but the table still sorts regardless of what I have in the function. Any help would be greatly appreciate. Thank you all.
Upvotes: 2
Views: 1086
Reputation: 61222
If you want complete control over the sort, add sort: 'event'
to the configuration options
Keep in mind, you're in control now, so you must sort the data manually.
The sortAscending
and sortColumn
options are used to set the sort arrow in the column heading.
In this example, the data is initially sorted by descending Hours, set the options accordingly on the initial draw.
Then in the sort event, I only allow sorting by Hours...
google.load("visualization", "1", {packages:["table"], callback: loadChart});
function loadChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Name');
data.addColumn('number', 'Salary');
data.addColumn('number', 'Hours');
data.addRows([
['Mike', {v: 10000, f: '$10,000'}, 40],
['Jim', {v:8000, f: '$8,000'}, 30],
['Alice', {v: 12500, f: '$12,500'}, 20],
['Bob', {v: 7000, f: '$7,000'}, 10]
]);
var chart = new google.visualization.Table(document.getElementById('table_div'));
var options = {
sort: 'event',
sortAscending: false,
sortColumn: 2
};
google.visualization.events.addListener(chart, 'sort', function(e) {
if (e.column === 2) {
options.sortAscending = e.ascending;
options.sortColumn = e.column;
data.sort([{
column: e.column,
desc: !e.ascending
}]);
chart.draw(data, options);
}
});
chart.draw(data, options);
}
<script src="https://www.google.com/jsapi"></script>
<div id="table_div"></div>
Upvotes: 2