Kamal Kant
Kamal Kant

Reputation: 1130

legends Click event not working after iteration

I am facing an issue with dimple.js. I created a stacked chart and I want to bind a click event into each of the legends of that chart. If a page reload then its working fine, but the moment when I changed the data of chart by a function call, its changing chart content fluently but legend click functionality is not working anymore. Please help to get rid out of this.

Note: I don't want to use the Jquery click handler function. I used the dimple Js selector. Below is the code which I have used also I have attached a fiddle link for the same. Fiddle Link

var svg = dimple.newSvg("#chartContainer", 590, 400);
var data = [
    { Animal: "Cats", Value: (Math.random() * 1000000) },
    { Animal: "Dogs", Value: (Math.random() * 1000000) },
    { Animal: "Mice", Value: (Math.random() * 1000000) },
    { Animal: "Rat", Value: (Math.random() * 1000000) },
    { Animal: "Cow", Value: (Math.random() * 1000000) }
];

var myChart = new dimple.chart(svg, data);
myChart.setBounds(60, 30, 510, 305)

var x = myChart.addCategoryAxis("x", "Animal");
x.addOrderRule(["Cats", "Dogs", "Mice"]);

myChart.addMeasureAxis("y", "Value");
myChart.addSeries("Animal", dimple.plot.bar);
myChart.addLegend(30, 100, 60, 300, "left");
myChart.draw();

svg.selectAll("rect").on("click",function(){
    console.log("Hello");
});

//svg.selectAll("g rect.legendKey").on("click",function(){
//  console.log("Hello");
//});
d3.select("#btn").on("click", function() {
   myChart.data = [
     { Animal: "Cats", Value: (Math.random() * 1000000) },
     { Animal: "Dogs", Value: (Math.random() * 1000000) },
     { Animal: "Mice", Value: (Math.random() * 1000000) }
   ];
   myChart.draw(1000);
});

Upvotes: 1

Views: 191

Answers (1)

rioV8
rioV8

Reputation: 28663

In your button click handler you have to bind the legend click handler to the new legend after the myChart.draw(1000);

function legendClick(){
    console.log("Hello");
}

d3.select("#btn").on("click", function() {
   myChart.data = [
     { Animal: "Cats", Value: (Math.random() * 1000000) },
     { Animal: "Dogs", Value: (Math.random() * 1000000) },
     { Animal: "Mice", Value: (Math.random() * 1000000) }
   ];
   myChart.draw(1000);
   svg.selectAll(".legendKey").on("click", legendClick);
});

Upvotes: 1

Related Questions