【问题标题】:D3- understanding the calling object for the d3 call() methodD3-了解d3 call()方法的调用对象
【发布时间】:2020-05-02 13:57:27
【问题描述】:

我是 d3 的新手,还在学习。 我有 nodelink 作为 d3 中的变量,它们从给定的 json 数据格式中选择相应的节点和链接/图形。 我编写了一个函数来根据每个链接的 sourcetarget 名称更改其颜色。 p>

我无法理解的是,在变量 node 上调用此函数也会改变链接的颜色。那么我在什么对象上调用这个函数是否重要呢? d 变量是否会根据我调用函数的内容在内部从节点更改为链接?

代码

//How link is defined
var link=svg
.append("g")
.selectAll("line")
.data(graph.links)
.enter()
.append("line")
.attr("stroke-width",function(d){
  return 3
})
.style("stroke","pink")
.text("text",function(d){return d.name});

//How node is defined
var node =svg
.append("g")
.selectAll("circle")
.data(graph.nodes)
.enter()
.append("circle")
.attr("r",5)
.attr("fill", function(d){
  return "orange"
})
.attr("stroke","yellow")
;

//link.call(updateState1)
//This works as it should

node.call(updateState1)
// I can't understand why this line works too.

function updateState1() {

    link
      .each(function(d) {
          var colors=["red","green","blue"]
          var num=0;
          if(d.source.name.length>d.target.name.length)
          {
              num=1;
              console.log("Inside 1");
              console.log("Source is ",d.source.name," and target is ",d.target.name);
          }
          else if(d.source.name.length<d.target.name.length)
          {
              num=2;
              console.log("Inside 2");
              console.log("Source is ",d.source.name," and target is ",d.target.name);
          }
          else{
            num=0;
          }
        // your update code here as it was in your example
        d3
        .select(this)
        .style("stroke", function(d){ return colors[num]})
        .attr('marker-end','url(#arrowhead)');
        
  
        
      });

      
  }

【问题讨论】:

    标签: javascript d3.js


    【解决方案1】:

    当您使用selection.call 时,函数的第一个参数是调用它的selection。所以如果你看:

    function updateState1() {
    
        link
          .each(function(d) {
    

    您可以看到您明确使用了link,这就是链接不断更新的原因。相反,如果您将其更改为:

    function updateState1(selection) {
    
        selection
          .each(function(d) {
    

    它应该使用来自selection.call 的选择(nodenode.call(updateState1) 的情况下)。

    如果您传递给selection.call 的函数不带任何参数,则相当于只调用函数本身(即如果fn 没有任何参数selection.call(fn)fn() 相同) .

    【讨论】:

    • 是的,但是从节点或链接调用它没有意义吗?
    • 是的,从你写的方式来看,node.call(updateState1) 应该等同于 updateState()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-19
    • 1970-01-01
    • 2012-05-04
    • 2014-05-12
    • 2014-11-24
    • 2021-02-03
    相关资源
    最近更新 更多