简体   繁体   中英

Use d3 data binding for a secondary effect?

I would like to call a function with each individual data point in my data set. This feels like it could be accomplished using d3 more cleanly than by simply looping through the dataset, and I've currently written something along the lines of the following:

<script>

data = [1,3,5,7]

        d3.selectAll('p')
            .data(data)
            .enter()
            .append('p')
            .text(function(d){
                someFunction(d)});

         function someFunction(x){
                console.log(x);
         }

</script>

However, since there is no need for me to actually create the 'p' elements, is there a way to simply call a function with the data elements as args themselves? I've tried using d3.data().enter().call() but can't quite get it to work.

To simply evaluate a function on a set of elements you can use forEach or map which returns an array with the return values evaluated on every element in the array.

function doSomething(d) {
  // do something here
  // console.log(d);
  return d + 1;
}

[1,2,3,4].forEach( doSomething );

var res = [1,2,3,4].map( doSomething );
// res => [2, 3, 4, 5]

Here is some more information about the D3 part:

The selectAll and select function return Selections. You can now modify the attributes of all elements.

// Selection
var $p = d3.selectAll('p');

The data method of a Selection returns a Join, which means it creates a join between the Selection and the data array.

// Join
var $$p = d3.selectAll('p').data([1,2,3,4]);

The enter and exit methods of a Join let you access the enter set (values in the data array that are not existing in the Selection) and the exit set (values in the Selection that are not existing in the data array). To get the update set, you can simply use the Join like a Selection.

// Enter a p element for every element in the enter set
$$p.enter().append('p');

// Update all p elements in the update set
$$p.attr('class', 'active');

// Remove all elements in the exit set
$$p.exit().remove();

The each method of a Join let's you iterate over the update set, passing each value from the data array as an argument.

$$p.each(function(d, i){
  // Current Selection
  d3.select(this);
  // Current data element
  d;
  // Index of the data element in the array
  i;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM