DojoD3PieChart.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. define([
  2. "dojo/_base/declare",
  3. "dojo/_base/lang",
  4. "dojo/_base/array",
  5. "./DojoD3",
  6. "./Mapping",
  7. "dojo/text!./templates/DojoD3PieChart.css"
  8. ], function (declare, lang, arrayUtil,
  9. DojoD3, Mapping,
  10. css) {
  11. return declare([Mapping, DojoD3], {
  12. mapping:{
  13. pieChart: {
  14. display: "Pie Chart Data",
  15. fields: {
  16. label: "Label",
  17. value: "Value"
  18. }
  19. }
  20. },
  21. constructor: function (mappings, target) {
  22. if (mappings)
  23. this.setFieldMappings(mappings);
  24. if (target)
  25. this.renderTo(target);
  26. },
  27. renderTo: function (_target) {
  28. _target = lang.mixin({
  29. css: css,
  30. innerRadiusPct: 0
  31. }, _target);
  32. this.inherited(arguments);
  33. this.SvgG
  34. .attr("transform", "translate(" + this.target.width / 2 + "," + this.target.height / 2 + ")")
  35. ;
  36. this.update([]);
  37. },
  38. display: function (data) {
  39. if (data)
  40. this.setData(data);
  41. var data = this.getMappedData();
  42. this.update(data);
  43. },
  44. update: function (data) {
  45. var color = d3.scale.ordinal()
  46. .range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"])
  47. ;
  48. var arcFunc = d3.svg.arc()
  49. .outerRadius(this.target.radius)
  50. .innerRadius((this.target.radius * this.target.innerRadiusPct) / 100)
  51. ;
  52. var pie = d3.layout.pie()
  53. .sort(null)
  54. .value(function(d) { return d.value; })
  55. ;
  56. var arc = this.SvgG.selectAll(".arc")
  57. .data(pie(data))
  58. ;
  59. var g = arc
  60. .enter().append("g")
  61. .attr("class", "arc")
  62. ;
  63. g.append("path")
  64. .attr("d", arcFunc)
  65. .style("fill", function (d) { return color(d.data.value); })
  66. .on("click", lang.hitch(this, function (d) {
  67. var evt = {};
  68. evt[this.getFieldMapping("label")] = d.label;
  69. this.emit("click", evt);
  70. }))
  71. ;
  72. g.append("text")
  73. .attr("transform", function(d) { return "translate(" + arcFunc.centroid(d) + ")"; })
  74. .attr("dy", ".35em")
  75. .style("text-anchor", "middle")
  76. .text(function (d) { return d.data.label; })
  77. ;
  78. arc.exit().remove();
  79. }
  80. });
  81. });