Get the DOM target from a drag and drop callback when "this" is not available

The documentation for d3.drag states that the DOM element of the drag event will be available in thisfor callback:

When the specified event is dispatched, each listener will be called with the same context and arguments as select.on listeners: the current datum d and index i, and this context is the current DOM element.

But my callback is an instance of an object, and thispoints to that object. So I need another way to access the current DOM element, which is usually passed to this. How can i do this?

+3
source share
1

, this, this :

d3.drag().on(typename, function(d, i, n) {
  //here, 'this' is simply n[i]
})

, , this . , .

, :

var data = d3.range(5)
var svg = d3.select("body")
  .append("svg")
  .attr("width", 400)
  .attr("height", 100);
var circle = svg.selectAll(null)
  .data(data)
  .enter()
  .append("circle")
  .attr("cy", 50)
  .attr("cx", function(d) {
    return 50 + 50 * d
  })
  .attr("r", 10)
  .attr("fill", "tan")
  .attr("stroke", "black")
  .call(d3.drag()
    .on("start", function(d, i, n) {
      console.log(JSON.stringify(n[i]))
    }))
<script src="https://d3js.org/d3.v4.min.js"></script>

PS: JSON.stringify D3, , console.log D3.


"this"

D3.js . .attr, .style, .text, .on .data, .

:

  1. (d)
  2. (i)
  3. (nodes)
  4. this DOM.

, , , D3.js ( d, i p D3 v3.x). this - :

.on("mouseover", function(){
    d3.select(this);
});

this, . , : https://jsfiddle.net/y5fwgopx/

ES6, . D3, this, : this. , this .

, , this D3. , , :

.on("mouseover", ()=>{
    d3.select(this);
});

, : https://jsfiddle.net/tfxLsv9u/

, : , , . , , ? , this D3?

, this - , nodes[i]. API D3, :

... this DOM (nodes[i])

: nodes DOM, i , nodes[i] DOM. this.

:

.on("mouseover", (d, i, nodes) => {
    d3.select(nodes[i]);
});

: https://jsfiddle.net/2p2ux38s/

+7

Source: https://habr.com/ru/post/1666134/


All Articles