Events Handling
Visualizations must be able to communicate and exchange information with the rest of the page. This is an even more vital function when you create dashboards that use multiple visualizations on the same page, all of them based on the same data. Users expect visualizations to react to changes that occur somewhere else in the page or inside another visualization.
To handle these cases, the Google Visualization API includes functions to fire and respond to events. Each visualization can fire events using the google.visualization.events.trigger() function, which takes three parameters:
- The source of the event (typically the visualization itself)
- A string representing the name of the event
- An object representing the event details (in the form of a key/value map)
Visualization users can listen to events using the google.visualization.events.addListener() function. It also takes three parameters:
- The visualization to which you want to listen
- The name of the events in which you are interested
- A callback function to handle the event (The event details will be passed as parameters to the function.)
The Select Event
The
select event is a special case. Visualizations use it to notify others that the user has selected a particular element of the underlying
DataTable and instructs them to react to selections that occur elsewhere. A visualization that wants to handle the
select event has to:
- fire events with the select name and no details whenever a user selects an item that maps to a particular cell, row, or column in the underlying DataTable.
- expose a getSelection() method that returns an array of selected items. Each selected item must be an object with row and/or column properties referring to the selected cell in the data. You can leave row or column set to null if the user selected an entire column or row.
- expose a setSelection() method if it wants to react to selections occurring outside itself. It receives a list of objects in the same format as the ones returned by getSelection().
Listing 5 illustrates how to extend the treemap visualization to fire select events.
You can now bind the treemap visualization and the organizational chart together by adding the following snippet to the web page example:
google.visualization.events.addListener(
treemap, 'select', function() {
orgchart.setSelection(treemap.getSelection());
});
Now, whenever a user clicks on a treemap node, the corresponding entry in the organizational chart will be highlighted.