Raf
Raf

Reputation: 684

How in d3.js pass current selection to .each() callback?

I have array of data and if I want to render this data as text I will use the next code

footer_item = svg_selection.append('g')
    .attr('class', 'footer_data')
    .selectAll('g')
    .data(data)
    .enter()
    .append('g')

footer_item.append('text')
  .text((d) => d)
  ...

What if instead of text I want to draw some shape. I can use this approach

footer_item
  .each((d) => {
    // draw some shape
    // don't know how to refer to footer_pointer
     draw_my_shape(footer_item_pointer, d.x, d.y);
  })

function draw_my_shape(footer_item_pointer, x, y){

    footer_item_pointer
      .append('circle')
      .attr('cx', x)
      .attr('cy', y)
      ... 
}

The only problem with this approach I will lose pointer to footer_item. I need pointer to footer_item to draw my shape inside g element.

Is it possible to send footer_item pointer with .each() function to my draw callback?

Can I use .call() function for that? I tried but then d variable will be contain full selection and full data. And I will come again to where I started.

Upvotes: 1

Views: 829

Answers (1)

M. Davis
M. Davis

Reputation: 709

If I understand correctly, you want to access footer_item inside of the each function. You can do this by not using an arrow function, and using the scope value of this in the function:

footer_item.each(function(d, i) {
        //"this" refers to the <g> html element that footer_item points to
        var foo = d3.select(this);
     });

You can then draw some more shapes on top of that selection:

foo.append('circle').attr(...
foo.append('rect').attr(...

Upvotes: 2

Related Questions