使用带有d3的箭头函数 [英] Using arrow functions with d3

查看:106
本文介绍了使用带有d3的箭头函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is it possible? I am not sure, since d3 makes heavy use of this rebindings and this seems to conflict with 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

不绑定到输入选择中的当前元素,而是绑定到 Window 对象):

While the following does not work as expected (this is not bound to the current element in the enter selection but to Window object):

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

You can use arrow functions if you don't need access to this of the current element.

回退到旧样式函数, code> this 当前元素。

Fallback to the old style functions for cases where you want to access this of the current element.

或使用显式绑定允许您的函数(非箭头函数)使用 .bind ()

Or use explicit binding to allow your function (not arrow function) to access whatever object you want using .bind()

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

To avoid working with this you have the option of using d3 name or class selectors to conveniently access any element. e.g.:

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

这篇关于使用带有d3的箭头函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆