Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a function once when data enters in d3

Tags:

d3.js

Is there a way to call a function when data enters using data().enter()?

For example, in this current jsfiddle: http://jsfiddle.net/p3m8A/4/ , I have a function that draws a group and I want to call this function when new data enters. The current jsfiddle doesn't do anything but the objective is to click on the red square and using .data.enter draw a purple square when the red square is clicked.

The specific part I'm trying to get to work is :

canvas.selectAll("#boxGroup")
    .data(data)
.enter().function(d,i) {
    drawBox(150,20,d);
};

Thanks

like image 588
user2534068 Avatar asked Jul 08 '13 17:07

user2534068


People also ask

What does enter() do in D3?

enter() function in D3. js is used to create the missing elements and return the enter selection. Syntax: selection.

What do the select () and selectAll () functions in D3 do?

d3. select selects the first matching element whilst d3. selectAll selects all matching elements. Both functions take a string as its only argument.

What does .data do in D3?

data() D3 is data driven. The data() function is used to join the specified array of data to the selected DOM elements and return the updated selection. D3 works with different types of data like Array, CSV, TSV, JSON, XML etc.


1 Answers

You want the method .call(function(d))

This will run your function once, passing d as the array of all of the data you have provided. i is not defined for using call after enter().

If you want to draw multiple boxes, based on d, your code would look something like this:

canvas.selectAll("boxGroup")
    .data(data)
    .enter()
    .call(function(d){drawBoxes(150,20,d);});

I've created a basic fiddle of this here.

Note that this is what you want to use if you want to call a function on the selection returned by .enter() in the same spot as you're using it. It's also possible to bind a function to the enter event of a given DOM element by using .on('enter',function), but this would require that the element that you are entering data into already exist.

like image 100
ckersch Avatar answered Sep 29 '22 11:09

ckersch