D3.js事件监听器无法访问“this”。当使用ES6箭头功能时 [英] D3.js event listeners cannot access "this" when ES6 arrow functions are used

查看:114
本文介绍了D3.js事件监听器无法访问“this”。当使用ES6箭头功能时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用具有箭头功能的D3.js事件监听器,但它似乎不起作用。

I'm trying to use D3.js event listeners with arrow functions, but it does not seem to work.

this 绑定到未定义

如何访问 使用ES6箭头功能?

How can I access this using ES6 arrow functions?

ES5:

svg.selectAll('circle')
  .data(data)
  .enter()
  .append('circle')
  .attr('r', '10')
  .attr('cx', (d) => x(d.day))
  .attr('cy', (d) => y(d.amount))
  .on('mouseenter', function (d) {
    console.log(this); // output '<circle r="10" cx="10" cy="1"/>'
  });

ES6(使用箭头功能):

ES6 (using arrow function):

svg.selectAll('circle')
  .data(data)
  .enter()
  .append('circle')
  .attr('r', '10')
  .attr('cx', (d) => x(d.day))
  .attr('cy', (d) => y(d.amount))
  .on('mouseenter', (d) => {
    console.log(this); // output: 'undefined'
  });


推荐答案

这是预期的行为。 (以下是我对解释这种行为的不良尝试。你可能会更好阅读本文

This is expected behaviour. (Below is my poor attempt at explaining this behaviour. You're likely better off reading this)

箭头函数所在的上下文( this )执行将是他们被定义的上下文(什么在函数之外)

The context (this) in which an arrow function is executed will be the context in which they are defined (What ever this is outside the function)

D3可能设置事件侦听器的上下文是发出事件的对象(如ES5示例中所示)。

D3 likely sets the context of your event listener to be the object which is emitting the event (As in your ES5 example).

但是,通过使用箭头函数,您强制将上下文绑定到您定义函数的上下文。在您的情况下,此上下文未定义/窗口,因为您的代码不包含在另一个函数中。

But, by using arrow functions, you are forcing the context to be bound to the context in which you defined the function. In your case, this context is undefined / window as your code is not contained within another function.

如果我将ES6示例转换回ES5,可能会更好地解释:

Perhaps it is better explained if I convert your ES6 example back into ES5):

var self = this;    
svg.selectAll('circle')
      .data(data)
      .enter()
      .append('circle')
      .attr('r', '10')
      .attr('cx', (d) => x(d.day))
      .attr('cy', (d) => y(d.amount))
      .on('mouseenter', (d) => {
        console.log(self); // output: 'undefined'
      });

我对你解决问题的建议很简单。使用常规函数作为您的活动订阅者(对于您的两个'attr'订阅者,使用箭头功能也没有任何好处。)

My advice to fix your issue is simple. Use a regular function as your event subscriber (There is also no benefit of using arrow functions for your two 'attr' subscribers).

svg.selectAll('circle')
  .data(data)
  .enter()
  .append('circle')
  .attr('r', '10')
  .attr('cx', (d) => x(d.day))
  .attr('cy', (d) => y(d.amount))
  .on('mouseenter', function(d) {
    console.log(this); // output '<circle r="10" cx="10" cy="1"/>'

  });

这篇关于D3.js事件监听器无法访问“this”。当使用ES6箭头功能时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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