【问题标题】:Using arrow functions with d3在 d3 中使用箭头函数
【发布时间】:2015-12-29 02:53:40
【问题描述】:

有可能吗?我不确定,因为 d3 大量使用 this 重新绑定,这似乎与 ES6 spec 冲突。

例如,以下工作正常:

// Working fine
var data = [1,2,3]
var svg = d3.select('body').append('svg').attr('height', 500).attr('width', 500).style('background-color', 'orange');
var gs = svg.selectAll('g').data(data).enter();
gs.append('circle')
    .attr('cx', function () { return Math.random()*500; })
    .attr('cy', function () { return Math.random()*500; })
    .attr('r', function () { return Math.random()*100; })
    .each(function () { console.log(this); });  // this is bound to the current element in the enter selection

虽然以下内容无法按预期工作(this 未绑定到输入选择中的当前元素,而是绑定到 Window 对象):

var data = [1,2,3]
var svg = d3.select('body').append('svg').attr('height', 500).attr('width', 500).style('background-color', 'blue');
var gs = svg.selectAll('g').data(data).enter();
gs.append('circle')
    .attr('cx', () => Math.random()*500)
    .attr('cy', () => Math.random()*500)
    .attr('r', () => Math.random()*100)
    .each(() => console.log(this)); // this is bound to Window object

相关小提琴here.

【问题讨论】:

  • @chriskelly 您的示例只是为选择中的所有元素设置相同的值,这不是我想要实现的(这就是为什么在每个元素的基础上使用函数)
  • 当我运行您的示例时,我看到的唯一区别是输出控制台日志。但是你为什么要访问this。这是一个有趣的问题,但我想知道一个问题所在。
  • @chriskelly 这是一个非常具体的用例(有一些我想重用的函数,它在 svg 组中创建复杂的元素结构,我需要this 知道我引用的是哪个组,其中将追加新元素)。

标签: javascript d3.js ecmascript-6


【解决方案1】:

如果你使用的是 d3v4,你可以像这样访问当前的 DOM 节点:

gs.append('circle')
    .attr('cx', () => Math.random()*500)
    .attr('cy', () => Math.random()*500)
    .attr('r', () => Math.random()*100)
    .each((d, i, j) => console.log(j[i])); 
        // j is current group, i is current index

【讨论】:

    【解决方案2】:

    如果您不需要访问当前元素的this,可以使用箭头函数。

    在您想要访问当前元素的this 的情况下,回退到旧样式函数。

    或者使用显式绑定来允许你的函数(不是箭头函数)使用.bind()访问你想要的任何对象

    为避免使用this,您可以选择使用 d3 名称或类选择器来方便地访问任何元素。例如:

    var stuffINeed = svg.selectAll('.someClass');
    

    【讨论】:

      【解决方案3】:

      无法修改箭头函数的行为。它们的绑定是“硬编码”的,不能通过使用bind 方法重新绑定或调用任何其他接受显式执行上下文的函数方法(例如apply)来更改。任何绑定函数都可以这样说——一旦绑定,返回的函数就会被绑定永远

      有可能吗?

      考虑到上述情况,如果 d3 使用binding 来提供方便的链接行为,那么在以某种方式修改 d3 的 API 以适应它们之前,使用箭头函数无法实现。 p>

      【讨论】:

        猜你喜欢
        • 2015-01-03
        • 1970-01-01
        • 1970-01-01
        • 2018-11-29
        • 2017-09-28
        • 2016-09-01
        • 2019-11-01
        • 2018-07-19
        • 1970-01-01
        相关资源
        最近更新 更多