Question

I am trying to change the simulation details dynamically in the D3 example at https://github.com/mbostock/d3/blob/master/examples/force/force-multi-foci.html. I put in a checkbox and then assign the tick handler dynamically as following (full code at http://pastebin.com/k4P0uzHK) :

$("#chkBox").change(function(){
  if ($(this).is(':checked')) {
    force.on("tick", forceTick);
  } else {
    force.on("tick", forceTick2);
  }
});

forceTick = function(e) {
  // Push different nodes in different directions for clustering.
  var ky = 400 * e.alpha;
  var kx = 20 * e.alpha;
  hLinks.forEach(function(hlink) {
    var yB = hlink.source.y, yT = hlink.target.y;
    if (yB<(yT+20)) { hlink.source.y += Math.min(ky,yT+20-yB); hlink.target.y -= Math.min(ky,yT+20-yB);}
    var xB = hlink.source.x, xT = hlink.target.x;
    if (xB<(xT-20)) { hlink.source.x += Math.min(kx,xT-20-xB); hlink.target.x -= Math.min(kx,xT-20-xB);}
    if (xB>(xT+20)) { hlink.source.x -= Math.min(kx,xB-xT-20); hlink.target.x += Math.min(kx,xB-xT-20);}

  });

  node.attr("cx", function(d) { return d.x; })
      .attr("cy", function(d) { return d.y; });

  link.attr("x1", function(d) { return d.source.x; })
       .attr("y1", function(d) { return d.source.y; })
       .attr("x2", function(d) { return d.target.x; })
       .attr("y2", function(d) { return d.target.y; });
};


forceTick2 = function(e) {

  node.attr("cx", function(d) { return d.x; })
      .attr("cy", function(d) { return d.y; });

  link.attr("x1", function(d) { return d.source.x; })
       .attr("y1", function(d) { return d.source.y; })
       .attr("x2", function(d) { return d.target.x; })
       .attr("y2", function(d) { return d.target.y; });
};

But actually the it seems that only the handler given first works. Is there a way to dynamically control the simulation?

No correct solution

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top