Data Key

2,561 views
Skip to first unread message

dizzy

unread,
Jun 28, 2011, 6:31:37 PM6/28/11
to d3-js
Hi,

At http://mbostock.github.com/d3/ it states the following:

"The key function also determines the enter and exit selections: the
new data for which there is no corresponding key in the old data
become the enter selection, and the old data for which there is no
corresponding key in the new data become the exit selection. The
remaining data become the default update selection."

I have some questions pertaining to this...
1. If you do not use a key, does that mean that every item is cleared
via the exit() function and then added again via the enter() function?
2. Is using a key then more efficient as it means certain items will
not be removed if there exists already a key for them?

Thanks

Mike Bostock

unread,
Jun 28, 2011, 6:36:02 PM6/28/11
to d3...@googlegroups.com
> 1. If you do not use a key, does that mean that every item is cleared
> via the exit() function and then added again via the enter() function?

No. If you do not use a key, the default key is the index: the first
data is mapped to the first element, and so on. Thus, if your new data
has more elements than the existing selection, the incoming data will
be available in the enter list, and the exit list will be empty;
likewise, if your new data has fewer elements, the outgoing elements
will be in the exit list and the enter list will be empty.

> 2. Is using a key then more efficient as it means certain items will
> not be removed if there exists already a key for them?

Using a key can be more efficient as you don't need to update elements
whose data does not change. Generally speaking, though, the key
function won't change the number of elements that enter or exit; key
functions are particularly important for preserving object constancy
across transitions, as in this tutorial:

http://mbostock.github.com/d3/tutorial/bar-2.html

Mike

dizzy

unread,
Jun 28, 2011, 6:50:03 PM6/28/11
to d3-js
Thanks Mike. looks like in my case using key is important as my x-
axis is a date and the data that is additive is typically older
chronologically. Without the key, the transition was rendering
backwards. Fixed now with the use of a key.
Reply all
Reply to author
Forward
0 new messages