Passing multiple Chart.js datasets via postMessage?

Hi, I am trying to update my Chart.js stacked bar chart, which is one bar with multiple values, however I cannot seem to update more than one dataset at a time. Could someone help me solve this? I assume properly passing multiple data points or, as a workaround, counting the message # (“n”) to then update value n in the bar chart could solve my issue (as I sketch below). Any pointers?


Relevant code from Chart.js
Code building the data

var myChart = new Chart(ctx, {
type: ‘horizontalBar’,
data: {
labels: [“Marginal Tax Rate”],
datasets: [{
label: ‘Federal’,
stack: ‘groupMarginal’,
data: [10],//start empty
backgroundColor: [
‘rgba(238, 232, 170, 0.2)’
],
borderColor: [
‘rgba(238, 232, 170, 1)’
],
borderWidth: 1
},{
label: ‘FICA’,
stack: ‘groupMarginal’,
data: [10],
backgroundColor: [
‘rgba(10, 168, 196, 0.2)’
],
borderColor: [
‘rgba(10, 168, 196, 1)’
],
borderWidth: 1
},{
label: ‘State’,
stack: ‘groupMarginal’,
data: [15],
backgroundColor: [
‘rgba(153, 50, 204, 0.2)’
]
//…four total data sets

Chart code to receive the message.

//messageCounter initialized as global variable
window.onmessage = function(event){
if (event.data && Array.isArray(event.data)) {
if (messageCounter === 0) {
myChart.data.datasets[0].data = event.data;
} else if (messageCounter === 1) {
myChart.data.datasets[0].data = event.data;
} else if (messageCounter === 2) {
myChart.data.datasets[0].data = event.data;
} else if (messageCounter === 3) {
myChart.data.datasets[0].data = event.data;
messageCounter = -1;
}
messageCounter = messageCounter + 1;
myChart.update();
}
else {
console.log(“HTML Code Element received a generic message:”);
console.log(event.data);
}
};

postMessage from js page

var num = {
2017: [3],
2018: [4],
2019: [5],
2020: [6]
};
$w(‘#taxChart’).postMessage(num[2017]);
$w(‘#taxChart’).postMessage(num[2018]);
$w(‘#taxChart’).postMessage(num[2019]);
$w(‘#taxChart’).postMessage(num[2020]);
$w(‘#taxChart’).onMessage((event2) => {

if (event2.data.type === ‘ready’) {
$w(‘#taxChart’).postMessage(num[2017]);
}
});

Hi, I just wanted to see if someone could take a look at my question?

1 Like

Anyone ever answered this question? i have the same one