0

I have a class where a function binds mouse events to SVG element:

class Chart {

  bindEvent() {

    this.svg.append('rect')
      .on('mousemove', () => {
        const mouseDate = scales.x.invert(d3.mouse(this)[0]);
      });

  }

}

Which then babel transpiles into:

var Chart = function () {
  function Chart() {
    _classCallCheck(this, Chart);
  }

  _createClass(Chart, [{
    key: 'bindEvent',
    value: function bindEvent() {
      var _this = this;

      this.svg.append('rect').on('mousemove', function () {
        var mouseDate = scales.x.invert(d3.mouse(_this)[0]);
      });
    }
  }]);

  return Chart;
}();

So within the event callback 'this' changes '_this' and I loose context. Is there a way to manage this issue?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Daniyal
  • 241
  • 1
  • 4
  • 11
  • 1
    I recommend to always read documentation before you use a new feature. It's beyond me how people can read/learn about arrow functions and *not* learn about how they resolve `this` at the same time. – Felix Kling Apr 01 '16 at 20:54

1 Answers1

2

Fat arrow works that way by definition. It's possibly cleanest to use a regular function instead.

Juho Vepsäläinen
  • 26,573
  • 12
  • 79
  • 105