追加/插入后可以重用 enter() 选择吗? [英] Can enter() selection be reused after append/insert?

查看:18
本文介绍了追加/插入后可以重用 enter() 选择吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个场景,我想使用数据连接为每个数据元素附加 2 个新元素.

I have a scenario where I want to use a data join to append 2 new elements for each data element.

我最初是这样做的:

var y = d3.selectAll("line")
    .data([123, 456]);

y.enter().append("line");  // assume attr and style set
y.enter().append("line");

y.transition()...

在我仔细考虑之前,我期望在我的过渡中使用的更新选择将包含来自输​​入选择的合并后的追加.但这当然不起作用,因为每个数据元素的选择中只有 1 个槽.

Before I thought it through, I was expecting that the update selection used in my transition would contain the merged appends from the enter selection. But of course this did not work because there's only 1 slot in the selection per data element.

所以我更改了代码,使其仍然使用相同的 enter() 选择两次,但随后为新元素重新选择以进行转换.

So I changed the code such that it still used the same enter() selection twice but then reselected for the new elements in order to do the transition.

这种方法有效,但我的问题是这是否是一种推荐的处理方式.我是否应该确保在追加/插入后停止使用 enter()?或者,只要我记得更新选择将只包含最后创建的元素,就可以使用它来创建多个元素吗?

This approach worked, but my question is whether or not this is a recommended way to go about things. Should I make sure to stop using enter() after I append/insert? Or is it OK do use it to create multiple elements as long as I remember that the update selection will only contain the elements created last?

如果事实证明这是错误的,有什么更好的方法可以实现这一目标?

If it does turn out that this is wrong, what is a better way to achieve this?

推荐答案

没有.数据连接的目的是将元素与数据同步,创建、删除或更新元素有必要的.如果创建元素两次,元素将不再与绑定的数据数组一一对应.

No. The purpose of the data-join is to synchronize elements with data, creating, removing or updating elements as necessary. If you create elements twice, the elements will no longer correspond one-to-one with the bound array of data.

如果你想让每个数据对应两个元素,那么先附加一个组(G)元素,建立从数据到元素的一对一映射.然后根据需要附加子元素.得到的结构是这样的:

If you want two elements to correspond to each datum, then append a group (G) element first to establish a one-to-one mapping from data to elements. Then append child elements as necessary. The resulting structure is like this:

<g>
  <line class="line1"></line>
  <line class="line2"></line>
</g>
<g>
  <line class="line1"></line>
  <line class="line2"></line>
</g>

例如:

var g = svg.selectAll("g")
    .data([123, 456]);

var gEnter = g.enter().append("g");
gEnter.append("line").attr("class", "line1");
gEnter.append("line").attr("class", "line2");

这篇关于追加/插入后可以重用 enter() 选择吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆