使用带有d3的箭头功能

jar*_*daf 18 javascript d3.js ecmascript-6

可能吗?我不确定,因为d3大量使用this重新绑定,这似乎与ES6 规范相冲突.

例如,以下工作正常:

// 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
Run Code Online (Sandbox Code Playgroud)

虽然以下内容不能按预期工作(this不是绑定到enter选择中的当前元素而是绑定到Windowobject):

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
Run Code Online (Sandbox Code Playgroud)

相关小提琴在这里.

chr*_*lly 11

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

如果要访问this当前元素,请回退到旧样式函数.

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

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

var stuffINeed = svg.selectAll('.someClass');
Run Code Online (Sandbox Code Playgroud)


小智 9

如果您使用的是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
Run Code Online (Sandbox Code Playgroud)