从子上下文中选择d3节点(例如计时器)

时间:2015-08-05 12:37:27

标签: javascript d3.js

我想知道从子上下文中选择d3节点的最简单方法,例如计时器 - 例如......

var nodeEnter = node
                .enter()           
                .append("g")
                .attr("class", "node")
                .on("mousedown", function(d) { 

                    //d3.select(this) returns the node here (SVGGElement)

                    pressTimer = window.setTimeout(function() { 
                        //d3.select(this, d3.select(this.parent), d3.select(this).parent return [object Window] here

由于我似乎无法在计时器内依赖d3.select(this),如果我想更新那里的节点的属性,那么我必须首先更改数据,然后更新所有具有selectAll(.node)语句的节点,例如......

d.node_ring_width = 12;

node.selectAll(".outlinecircle").attr("stroke-width", function(d) { 
                                        return d.node_ring_width; 
});

有没有人知道更好的方法来拉取父上下文并让我直接访问节点?谢谢你的任何想法!

1 个答案:

答案 0 :(得分:1)

您可以使用closure保存this的值。然后,您就可以在提供给this的回调中访问.setTimeout()的原始值。

var nodeEnter = node.enter()           
                    .append("g")
                    .attr("class", "node")
                    .on("mousedown", function(d) { 

                        var self = this;  // Save the reference to this

                        pressTimer = window.setTimeout(function() { 
                            // self contains the saved reference
                            d3.select(self);
                            d3.select(self.parentNode);
                        }, 1000);
                    });