使用方法链接时 D3 的不同行为
D3 different behavior when using method chaining
我有一个对象负责生成 d3 图表:
this.svg = elem
.selectAll("svg")
.data([{}])
.enter()
.append("svg")
this.axis = this.svg
.append("g")
.attr("class", "axis")
// weird block
this.axis
.selectAll("g.axis-y")
.data([{}])
.append("g")
.attr("class", "axis-y")
this.axis
.selectAll("g.axis-y")
.attr("transform", "translate(100,0)")
.call(yAxis)
此表单中的代码不会生成 yAxis
。故障在标记为怪异块的块中。
如果我将那个更改为:
this.axis
.selectAll("g.axis-y")
.data([{}])
this.axis
.append("g")
.attr("class", "axis-y")
那么一切都会成功的。我只将长方法链分成两个单独的块。
两者不应该是平等的吗?有人可以解释为什么我有这两种不同的行为吗?
原因是因为在您的第一个代码示例中,您从数据(不存在)附加到元素 return,而在第二个代码示例中,您附加到 this.axis
元素,您的代码中的元素是 svg
元素 (this.axis = this.svg
).
为了使第一个示例正常工作,您需要在调用 data()
之后调用 enter()
,如下所示:
this.axis
.selectAll("g.axis-y")
.data([{}]).enter()
.append("g")
.attr("class", "axis-y")
希望这对您有所帮助。
this.axis
.selectAll("g.axis-y")
.data([{}])
this.axis
.append("g")
.attr("class", "axis-y")
与
不同
this.axis
.selectAll("g.axis-y")
.data([{}])
.append("g")
.attr("class", "axis-y")
这是一样的...
var thisAxis = this.axis
.selectAll("g.axis-y")
.data([{}])
thisAxis
.append("g")
.attr("class", "axis-y")
我有一个对象负责生成 d3 图表:
this.svg = elem
.selectAll("svg")
.data([{}])
.enter()
.append("svg")
this.axis = this.svg
.append("g")
.attr("class", "axis")
// weird block
this.axis
.selectAll("g.axis-y")
.data([{}])
.append("g")
.attr("class", "axis-y")
this.axis
.selectAll("g.axis-y")
.attr("transform", "translate(100,0)")
.call(yAxis)
此表单中的代码不会生成 yAxis
。故障在标记为怪异块的块中。
如果我将那个更改为:
this.axis
.selectAll("g.axis-y")
.data([{}])
this.axis
.append("g")
.attr("class", "axis-y")
那么一切都会成功的。我只将长方法链分成两个单独的块。 两者不应该是平等的吗?有人可以解释为什么我有这两种不同的行为吗?
原因是因为在您的第一个代码示例中,您从数据(不存在)附加到元素 return,而在第二个代码示例中,您附加到 this.axis
元素,您的代码中的元素是 svg
元素 (this.axis = this.svg
).
为了使第一个示例正常工作,您需要在调用 data()
之后调用 enter()
,如下所示:
this.axis
.selectAll("g.axis-y")
.data([{}]).enter()
.append("g")
.attr("class", "axis-y")
希望这对您有所帮助。
this.axis
.selectAll("g.axis-y")
.data([{}])
this.axis
.append("g")
.attr("class", "axis-y")
与
不同this.axis
.selectAll("g.axis-y")
.data([{}])
.append("g")
.attr("class", "axis-y")
这是一样的...
var thisAxis = this.axis
.selectAll("g.axis-y")
.data([{}])
thisAxis
.append("g")
.attr("class", "axis-y")