d3/d3-drag

"this" do NOT refer to dragged element in event-listener of d3.drag.on()

tarepan opened this issue · 1 comments

abstract

"this" do NOT refer to dragged element in event-listener of d3.drag.on(*, event-listener) when I use "arrow function" for event-listener.
If I use normal function (e.g. function(){...}), it seems normal.
I think this problem is related to this-binding in arrow function.
I don't good at "this" binding, so I hope someone fix this bug(bug?) or write it in document.

problem

"this" do NOT refer to dragged element in event-listener of d3.drag.on(*, event-listener) when I use "arrow function" for event-listener.
I wrote and upload sample on bl.ocks.org => sample

In event-listener of d3.drag().on(*, event-listener), "this" should refer to current DOM element.

from_API_reference ... listener will be invoked ... with the this context as the current DOM element.

But, when I use "arrow function" for event-listener, "this" do NOT refer to the current DOM element, instead, refer to "Window object".

// code for explanation. I do NOT check this code work or not. Sample in bl.ocks.org is checked to work.
<div id=div1>div1</div>
<div id=div2>div2</div>
d3.select("#div1").call(d3.drag().on("start", function(){console.log(this);})); // -> "<div>" ◎  
d3.select("#div2").call(d3.drag().on("start", ()=>{console.log(this);})); // -> "Window" !?

condition

  • PC: Microsoft sarface Pro (1)
  • OS: Windows 10
  • browser: google Chrome 55.0.2883.87 m (64-bit)

cause

I am not good at javascript grammar, so I have no confident to my opinion.
I think this problem is related this-binding of arrow function.
I am glad if this opinion is useful for bag-sweepers.

hope

If can, please someone fix this bug (bug?).
Even if that is difficult, please write this phenomenon in document.
I hope this issue will helpful for d3.js users (this is my first issue to github lol).

See the documentation for arrow functions.

Please use Stack Overflow tag d3.js to ask for help. Although I make an effort to assist everyone that asks, I am not always available to provide help promptly or directly. Stack Overflow provides a better collaborative forum for self-help: tens of thousands of D3-related questions have already been asked there, and some answered questions may be relevant to you.

When asking for help, please include a link to a live example that demonstrates the issue, preferably on bl.ocks.org. It is often impossible to debug from code snippets alone. Isolate the issue and reduce your code as much as possible before asking for help. The less code you post, the easier it is for someone to debug, and the more likely you are to get a helpful response.

If you have a question about D3’s behavior and want to discuss it with other users, also consider the d3-js Google Group or joining the d3-js Slack.

Thank you! 🤗