首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >D3-理解d3 call()方法的调用对象

D3-理解d3 call()方法的调用对象
EN

Stack Overflow用户
提问于 2020-01-15 18:26:45
回答 1查看 774关注 0票数 2

我是d3的新手,而且还在学习。我将节点链接作为d3中的变量,从给定的json数据格式/graph中选择各自的节点和链接。我编写了一个函数,根据每个链接的源、目标名称更改其颜色。

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

代码

代码语言:javascript
复制
//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)');
        
  
        
      });

      
  }
EN

回答 1

Stack Overflow用户

发布于 2020-01-15 18:38:56

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

代码语言:javascript
复制
function updateState1() {

    link
      .each(function(d) {

您可以看到您正在显式地使用link,这就是链接被更新的原因。相反,如果将其更改为:

代码语言:javascript
复制
function updateState1(selection) {

    selection
      .each(function(d) {

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

如果传递给selection.call的函数不带任何参数,则相当于调用函数本身(也就是说,如果fn没有任何参数,selection.call(fn)fn()相同)。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59757537

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档