- D3.js 4.x Data Visualization(Third Edition)
- ?ndrew Rininsland Swizec Teller
- 389字
- 2021-07-02 23:20:26
Joining data to selections
We've made it to the fun part of our DOM shenanigans. Remember when I said HTML is data visualization? Joining data to selections is how that happens.
To join data with a selection, we use the .data() function. It takes a data argument in the form of a function or array, and optionally a key function, telling D3 how to differentiate between various parts of the data.
When you join data to a selection, one of the following three things will happen:
- There is more data than there are selected elements (the length of the data is longer than the length of a selection). You can reference the new entries with the .enter() function
- There is exactly the same amount of data as before. You can use the selection returned by .data() itself to update element states
- There is less data than before. You can reference these using the .exit() function
- New in D3 v4 is the .merge() function, which allows you to to perform operations on selections containing both new and updating elements
You can't chain .enter() and .exit() because they are just references and don't create a new selection, but you can chain .enter() and .merge(). This means that you will usually want to focus on .enter() and .exit() and handle the three cases separately.
You must be wondering, how's it possible for there to be both more and less data than before? That's because selection elements are bound to each inpidual datum, not their number. If you shifted an array (that is, removed its first element) and then pushed a new value (or, added a new element to the end of an array), the previous first item would go to the .exit() reference and the new addition would go to the .enter() reference. This is tremendously powerful, as it allows D3 to track data as it changes in our projects without us having to write a lot of repetitive code.
Datum is the singular of data. You know that d argument we usually pass in the callback functions? That's what it stands for! It's also worth noting that there's a selection.datum() method that can accept a single object that you want to apply to all the items in a selection.
Let's build something cool with data joins and HTML.
- 軟件安全技術
- Java Web基礎與實例教程(第2版·微課版)
- OpenCV 3和Qt5計算機視覺應用開發
- RTC程序設計:實時音視頻權威指南
- SQL語言從入門到精通
- Python神經網絡項目實戰
- C語言課程設計
- 網站構建技術
- 運用后端技術處理業務邏輯(藍橋杯軟件大賽培訓教材-Java方向)
- FPGA Verilog開發實戰指南:基于Intel Cyclone IV(進階篇)
- LabVIEW虛擬儀器程序設計從入門到精通(第二版)
- Flask Web開發:基于Python的Web應用開發實戰(第2版)
- Machine Learning for OpenCV
- Solr權威指南(下卷)
- 虛擬現實建模與編程(SketchUp+OSG開發技術)