Multiple instances of d3 force layout on the same page

这一生的挚爱 提交于 2019-12-01 05:54:46

I wrote a tool that allows browsing biological regulatory networks, showing two SVG panels side-by-side. Each panel contains a force-layout network, as drawn by the d3.js API.

I found that the key to making this work is to give every element in the DOM a unique name, where there can be duplication.

In my case, I used _left and _right as suffices to every panel element, where the element is in the left or right panel, respectively. It is a lot of work to keep track of, but the network renderer can target its calls and events to the correct element and network.

In your case:

.attr("id", function(d,i) {
      return ("idx" + i);
      })

You want to replace the return value with something that uniquely addresses the network that the node is associated with. Whether you use a index numbering scheme or a suffix-based approach, like I did, the trick is to make sure all id names are unique.

Javascript is notorious for obfuscating whether state is shared or not. Your minimal example is no longer available, but when I encountered the same problem, my conclusion was that I was only making shallow copies where I needed complete clones. (I'm talking about the links and nodes that D3 takes as input.)

Without a true copy, the resulting behavior will be a bit random, as you discovered, depending on whether D3 code choses to modify any shared data "in situ" or not. In general, D3 tries not to create copies, for performance reasons.

This is why the json call workaround works: by completely stringifying all the data, you are de facto forcing a clone operation.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!