Joins
在D3中, 我們是動態(tài)創(chuàng)建dom元素。一般可以使用append來創(chuàng)建單一元素:
const svg = d3.select("svg");
svg.append("circle").attrs({ cx: 5, cy: 5, r: 2.5 });
而如果要根據(jù)數(shù)組進行批量創(chuàng)建dom, 則需要以下寫法:
const svg = d3.select("svg");
svg.selectAll('circle').data([20, 30, 40])
.enter().append('circle')
.attrs({ cx: d => d, cy: d => d, r: 5 });
而這里所有的疑惑, 都可使用下圖進行解答:

image.png
- 首先, 我們使用svg.selectAll('circle')產(chǎn)生一組空的選擇器。
- 選擇器選擇和數(shù)據(jù)進行綁定,這時候會產(chǎn)生三個操作:enter,update和exit。依據(jù)數(shù)據(jù)數(shù)據(jù),enter依次對應(yīng)數(shù)組中的每個元素,使用append產(chǎn)生update效果,在循環(huán)結(jié)束后,使用exit退出。
Key Function
一般情況下,我們使用data時候,要保證數(shù)組數(shù)據(jù)的順序。如果是數(shù)組,則默認索引。如果數(shù)組的元素為一個字典,則需要提供一個key(因為字典是無序的)。
考慮以下的代碼:
const otherData = [{value: 65}, {value: 35}, {value: 95}];
const svg = d3.select("svg");
svg.selectAll('circle').data(otherData)
.enter().append('circle')
.attrs({ cx: d => d.value, cy: d => d.value + 100, r: 5 });
這樣會在界面上生成三個circle(圖1)。雖然字典是無序的,但是不需要和已繪制的circle進行匹配,所以不需要key function.

1.png
在上述代碼前面增加以下代碼:
svg.selectAll('circle').data(data)
.enter().append('circle')
.attrs({ cx: d => d, cy: d => d, r: 5 });
這樣會生成新的三個circle,圖1的circle消失了。這是因為存在圖1的代碼情況下,圖2的代碼需要key function明確保證數(shù)組的順序,否則無法繪圖。
當我們加入:
.data(otherData, d => d.value)
后,圖1和圖2均顯示出來。

1.png
Enter, Update and Exit
Update: 提供數(shù)據(jù),存在匹配的元素
Enter: 提供數(shù)據(jù),不存在匹配的元素。
Exit: 提供元素,沒有匹配的數(shù)據(jù)。
const data = [35, 65, 95];
const divs = d3.select('.chart').selectAll('p').data(data);
divs.enter().append('p').text(d => d);
const d1 = d3.select('.chart').selectAll('p').data([35, 65]);
d1.exit().remove();
- 第一個divs,提供了update/enter的說明。
- 而d1中,由于只提供了前兩個數(shù)據(jù),經(jīng)過exit.remove后,會刪除第三條數(shù)據(jù)。
- 假設(shè)我們編寫如下的代碼(d1將做無用功),將不匹配的數(shù)據(jù)重新加入到頁面中,則頁面依舊保留三條數(shù)據(jù):
d1.exit().enter().append('p').text(d => d);