将数据绑定到 D3 中的父节点,而不是选择 -- 模式

binding data to parent node in D3 instead of selection -- pattern

本文关键字:选择 模式 父节点 数据绑定 D3      更新时间:2023-09-26

抽象"组件"时,D3 中推荐的模式是什么?

假设我有一个清单。通常我会做

d3.select('ol')
  .selectAll('li')
  .data(array)
  .enter()
  .append('li')
  .text(_.property('label'))

但是,当将其抽象为组件时,在使用的地方,我只想做

d3.select('ol')
  .data(array)
  .call(component)

问题是数据需要绑定到.selectAll,所以人们需要在使用的地方做.selectAll,但这违反了抽象(人们需要知道这个组件将附加什么类型的元素(

有趣的提议。
我实现了这样的"组件"并检查它是否正常工作。
(源代码为我的测试进行了一些修改。
我想知道不使用__data__的解决方案...

var array = [
    {label: 'label1'},
    {label: 'label2'},
    {label: 'label3'},
    {label: 'label4'},
    {label: 'label5'}
]
function component(selection) {
    selection.selectAll('li')
        .data(selection.datum()) // edited to use .datum() instead of selection[0][0].__data__
        .enter()
        .append('li')
        .text(_.property('label'))
}
d3.select('ol')
    .datum(array)
    .call(component)