繁体   English   中英

使用带有d3的箭头功能

[英]Using arrow functions with d3

可能吗? 我不确定,因为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

虽然以下内容不能按预期工作( 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

相关小提琴在这里

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

退回到旧风格功能要访问的情况下this当前元素。

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

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

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

如果您使用的是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

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

可能吗?

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM