I need to build an object string by string, and then use eval() to create the object.
I was successful doing this with an array of objects, but the next part, an object, is not working.
These three jsFiddles show the progression:
Chart with normal array (pieData) and object (pieOptions)
Chart with array formed of strings - works
Add object formed of strings - no work
There is considerable discussion about why I use eval(). The array and object used for data and options respectively are both formed bit-by-bit as strings, and then glomped together into an array and an object. This jsFiddle will demonstrate a (simpler) version of my problem:
http://jsfiddle.net/81fpdc44/3/
Please show me how to make s1...s5 into an array without using eval(). Am I missing something (not an uncommon situation...) ?
For Posterity: The code
Working (array):
<canvas id="pieChart" height="400" width="300"></canvas>
pieD = '{value:25, color:"red"},';
pieD += '{value:5, color:"blue"},';
pieD += '{value:25, color:"palegreen"},';
pieD += '{value:10, color:"darkcyan"},';
pieD += '{value:35, color:"wheat"}';
eval('pieData = ['+pieD+']');
var pieOptions = {
annotateDisplay : true,
segmentShowStroke : false,
segmentStrokeColor : "white",
segmentStrokeWidth : 1,
percentageInnerCutout : 0,
animation: false,
animationSteps : 100,
animationEasing : "easeOutQuart",
animateRotate : true,
animateScale : false,
legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<segments.length; i++){%><li><span style=\"background-color:<%=segments[i].fillColor%>\"></span><%if(segments[i].label){%><%=segments[i].label%><%}%></li><%}%></ul>"
};
var ctx = document.getElementById("pieChart").getContext("2d");
var myPieChart = new Chart(ctx).Pie(pieData,pieOptions);
Not working:
pieO = 'annotateDisplay : true,';
pieO += 'segmentShowStroke : false,';
pieO += 'segmentStrokeColor : "white",';
pieO += 'segmentStrokeWidth : 1,';
pieO += 'percentageInnerCutout : 0,';
pieO += 'animation: false,';
pieO += 'animationSteps : 100,';
pieO += 'animationEasing : "easeOutQuart",';
pieO += 'animateRotate : true,';
pieO += 'animateScale : false,';
pieO += 'legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<segments.length; i++){%><li><span style=\"background-color:<%=segments[i].fillColor%>\"></span><%if(segments[i].label){%><%=segments[i].label%><%}%></li><%}%></ul>"';
eval('pieOptions = {'+pieO+'}');
JSON.parsemethod for parsing the string. What you are trying to do is madness. It's very fragile, error-prone and an anti-pattern.