Reputation: 3
I'm trying to draw multiple linear chart, I am using a socket.io connection to receive multiple Data (MQTT messages) from different sensors. The problem is that I cannot find a way to reuse the code for every chart, this is what I have so far:
var socket = io();
var chartData = [];
chart_config = {
"type": "serial",
"theme": "light",
"fontFamily": "sans-serif",
"fontSize" : "12",
"valueAxes": [{
"id": "v1",
"position": "left"
}],
"mouseWheelZoomEnabled": true,
"graphs": [{
"id": "g1",
"bullet": "round",
"bulletBorderAlpha": 1,
"bulletColor": "#FFFFFF",
"useLineColorForBulletBorder": true,
"hideBulletsCount": 50,
"valueField": "value",
"balloonText": "[[value]]",
"balloon":{
"drop":true
}
}],
"chartCursor": {
"limitToGraph":"g1"
},
"categoryField": "date",
"categoryAxis": {
"equalSpacing": true,
"dashLength": 1,
"minorGridEnabled": true
},
"dataProvider": chartData,
"export": {
"enabled": true
}
};
var chart = AmCharts.makeChart("V1_chart", chart_config);
socket.on('panel1_V', function (data) {
var newDate = new Date();
chartData.push({
date: newDate,
value: data.message
});
console.log('mqtt message: ' + data.message);
console.log(JSON.stringify(chartData));
if (chartData.length > 20) {
chartData.splice(0, chartData.length - 20);
}
chart.validateData();
});
thanks for the help in advance.
Upvotes: 0
Views: 1171
Reputation: 6162
You will need to do a deep clone of the configuration object for every chart, keep the original unused.
The code below is an example how to clone the object in case you don't have a helper to do it.
/**
* Define function for cloning objects
* Taken from: http://stackoverflow.com/questions/728360/most-elegant-way-to-clone-a-javascript-object
*/
function clone(obj) {
var copy;
// Handle the 3 simple types, and null or undefined
if (null == obj || "object" != typeof obj) return obj;
// Handle Date
if (obj instanceof Date) {
copy = new Date();
copy.setTime(obj.getTime());
return copy;
}
// Handle Array
if (obj instanceof Array) {
copy = [];
for (var i = 0, len = obj.length; i < len; i++) {
copy[i] = clone(obj[i]);
}
return copy;
}
// Handle Object
if (obj instanceof Object) {
copy = {};
for (var attr in obj) {
if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]);
}
return copy;
}
throw new Error("Unable to copy obj! Its type isn't supported.");
}
/**
* Create first chart
*/
// create a copy of the universal config
var chartConfig1 = clone(chartConfig);
Please check this example: https://www.amcharts.com/kbase/reusing-the-same-config-object-for-multiple-charts/
Upvotes: 1