简体   繁体   中英

Is the order of the “.on” functions important in D3?

I have a circle whose color should change to red when clicked on. I also want to invoke a second function: "second click function" on the same click.

My problem is, at this stage only the second ".on" exectues, but ignores the first ".on", that means, the color does not change.

 var newcircle = svg.append("circle")
     .data(nodes)
     .attr("cx", 33)
     .attr("cy", 44)
     .attr("r", 33)
     .style("fill", "red")   
     .on("click", function(){d3.select(this).style("fill", "green");})   
     .on("click", function(d) { "second click function" } )

If I change the order of the ".on" functions into this:

 var newcircle = svg.append("circle")
     .data(nodes)
     .attr("cx", 33)
     .attr("cy", 44)
     .attr("r", 33)
     .style("fill", "red")        
     .on("click", function(d) { "second click function" })  
     .on("click", function(){d3.select(this).style("fill", "green");})

then it only changes the color, but not doing the "second click function".

Can anyone help me out?

You are binding an event of "click" to en element using the .on function. By adding a second definition of the event, the previous one is overwritten for that element.

To execute another function within your event handler, just invoke it within the function body of your event callback:

function resetCircleColor(ref){
  // do whatever you need to here, like set the fill color to green:
  // this assumes you are passing the correct reference to the circle
  // you want to change as the paramter 'ref'
  ref.style("fill", "red");
}
var newcircle = svg.append("circle")
  .data(nodes)
  .attr("cx", 33)
  .attr("cy", 44)
  .attr("r", 33)
  .style("fill", "red")

.on("click", function(){
  d3.select(this).style("fill", "green");
  resetCircleColor(circleref);
});

As https://github.com/d3/d3-selection/blob/master/README.md#selection_on explains,

If an event listener was previously registered for the same typename on a selected element, the old listener is removed before the new listener is added.

But it's simple to solve the problem; just add all the logic into one function.

.on("click", function(){
  d3.select(this).style("fill", "green");
  "second click function"
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM