Looker Studio 會使用 postMessage 介面,將資料和樣式資訊提供給含有社群視覺化效果的 iframe。本指南將詳細說明如何使用輔助程式庫。
對於社群視覺呈現,ds-component 具有兩項功能。
- 取得 iframe 的尺寸
- 管理 Looker Studio 的通訊
訂閱活動
當使用者與圖表互動時 (例如變更所選欄位、樣式或調整元件大小),Looker Studio 會將事件傳送至圖表。
dscc.subscribeToData 會註冊回呼,針對 Looker Studio 的每個 postMessage 事件叫用。回呼會傳遞 data 物件。
function drawViz(data){
// obtain the height and width to scale your visualization appropriately
var height = dscc.getHeight();
var width = dscc.getWidth();
// write your visualization code here
console.log("I'm the callback and I was passed this data: " + JSON.stringify(data, null, ' '));
}
// call drawViz every time Looker Studio sends a new postMessage
dscc.subscribeToData(drawViz, {transform: dscc.objectTransform});
傳回的資料
這兩種資料轉換都會傳回含有五個鍵的物件。
| 鍵 | 目的 |
|---|---|
style |
使用者選取的樣式資訊和預設樣式資訊 |
fields |
使用者選取的欄位資訊 |
interactions |
使用者選取的互動 |
theme |
報表主題資訊 |
tables |
資料列 |
dateRanges |
預設和比較日期範圍 |
資料格式:
{
fields: object(fieldsByConfigId),
style: object(styleById),
interactions: object(interactionsById),
theme: object(themeStyle),
tables: object(tablesById),
dateRanges: object(dateRangesById),
}
不同的視覺化圖表需要不同的資料格式。兩種常見格式為陣列的陣列或物件的陣列。ds-component 程式庫提供兩種轉換,可直接將資料轉換為這些格式。
這兩種轉換都記錄在 library-reference 中。這些轉換作業可輕鬆對應至 JavaScript 視覺化程式庫常用的資料格式。支援的轉換作業有兩種:objectTransform (傳回物件陣列) 和 tableTransform (傳回陣列的陣列)。
dscc.objectTransform
部分視覺化圖表會將資料視為物件陣列。
例如:
var data = [
{'colA': 'hello', 'colB', 'world'},
{'colA': 'hello', 'colB', 'world'}
];
以下程式碼顯示如何從 dscc.objectTransform 格式存取物件陣列。
function drawViz(data){
// what the object transform could look like
// [
// {'configId1': ['hello'], 'configId2': [1] },
// {'configId1': ['world'], 'configId2': [2] }
// ]
var dsccObjectTransformData = data.tables.DEFAULT;
// creating an array of objects
var arrayOfObjects = dscc.ObjectTransformData.rows.map(function(d){
return {
'configId1': d.configId1[0],
'configId2': d.configId2[0]
};
};
}
如果定義的資料區段允許使用者輸入多個欄位 (例如,為桑基圖定義了兩個維度),則轉換作業會視您的用途而定,因為 Looker Studio 傳回的資料格式會更像這樣:
var dsccObjectTransformData = [
{'configId1': ['hello', 'there'], 'configId2': [1] },
{'configId1': ['world', 'globe'], 'configId2': [2] }
]
dscc.tableTransform
部分視覺化程式庫會預期收到陣列的陣列。
例如:
var data = [
['hello', 1],
['world', 2]
];
下列程式碼顯示如何從 dscc.tableTransform 格式存取資料列。
function drawViz(data);
// what the below object looks like
// {
// headers: [{
// "id": "qt_ky8sltutsb",
// "name": "dimension",
// "type": "TEXT",
// "concept": "DIMENSION",
// "configId": "configId1"
// }, {
// "id": "qt_m9dtntutsb",
// "name": "metric",
// "type": "NUMBER",
// "concept": "METRIC",
// "configId": "configId2"
// }],
// rows: [
// ['hello', 1],
// ['world', 2]
// ];
// }
var dsccTableTransformObject = data.tables.DEFAULT;
// accessing the row of rows
var rowOfRows = dsccTableTransformObject.rows;
// accessing the header row
var headers = dsccTableTransformObject.headers;
}
dscc.subscribeToData(drawViz, {transform: tableTransform});