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

标签 javascript design-patterns d3.js

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

假设我有一个列表。通常我会这样做

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

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

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

问题在于数据需要绑定(bind)到.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)

关于javascript - 将数据绑定(bind)到D3中的父节点而不是选择--模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27526769/

相关文章:

javascript - 重新加载多个数据表的内容

javascript - Rivescript:在条件响应中使用关键字触发器

c++ - 单例同步 C++

asp.net-mvc - 构建 ASP.net MVC 应用程序以使用存储库和服务

oop - 装饰器设计模式问题?

javascript - d3 force layout固定节点之间的链接

javascript - 让框架触发其父框架中的函数

javascript - 使用 url 获取所有评论的列表?

javascript - 水平 d3 树 : how to have root starting at top left instead of middle y-axis?

javascript - 影响 d3.mouse 点的父 css 变换