Looker 数据洞察使用 postMessage 接口向包含社区可视化图表的 iframe 提供数据和样式信息。本指南详细介绍了如何使用帮助程序库。
对于社区可视化图表,ds-component 提供两项功能。
- 获取 iframe 的尺寸
- 管理与 Looker Studio 的通信
订阅事件
当用户与您的可视化图表互动(例如更改所选字段、样式或调整组件大小)时,Looker 数据洞察会向您的可视化图表发送事件。
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});