Detecting the datasources in a workbook using the Tableau JS API

It’s not immediately apparent when getting started with the Tableau JavaScript API that when you initialize and set a callback function using onFirstInteractive that an object is actually passed to the callback. This object has a getViz() method that let’s you get the Viz object that was just created. Once you have the Viz object, you can use its other methods to get information out.


var options = {
// This function runs after the viz is loaded, so all additional API calls should generate from there
onFirstInteractive : completeLoad,
toolbarPosition : tableau.ToolbarPosition.TOP
};

viz = new tableau.Viz( $("#tableauViz").get(), vizUrl, options);

function completeLoad(e) {

viz = e.getViz();
workbook = viz.getWorkbook();
active_sheet = workbook.getActiveSheet();

}

getActiveSheet() can return either a Dashboard or a Worksheet object. The easiest way to detect is to look for the getWorksheets method, which is only present on a Dashboard object. On a dashboard, you can iterate through the sheets and then use the getDataSourcesAsync() method on each sheet.

Iterating through is only necessary if you are concerned about what is the Primary data source on different sheets. In the same workbook, getDataSourcesAsync() will return all data sources on every sheet, even if there is no data blending occurring. It does not appear to be possible to detect when a secondary data source is actually in use (data blending) vs. just part of the workbook overall.


// Detect if active sheet is a Dashboard
if (active_sheet.getWorksheets){
// Dashboard
published_sheets = active_sheet.getWorksheets();
for (i=0;i<published_sheets.length;i++){
published_sheets[i].getDataSourcesAsync().then(
function (e){
console.log(e);
for(j=0;j<e.length;j++){
ds_name = e[j].getName();
ds_is_primary = e[j].getIsPrimary();
fields = e[j].getFields();

}
}
);
}
}
else{
// Worksheet
active_sheet.getDataSourcesAsync().then(
function (e){
console.log(e);
for(j=0;j<e.length;j++){
ds_name = e[j].getName();
ds_is_primary = e[j].getIsPrimary();
fields = e[j].getFields();
}
}
);
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s