D3.js keyword function executed twice on a simple selector / array combination

Studying d3, and when I create a simple array of numbers, then try to bind the data to a simple set of elements, but use the key function, it runs through the loop twice. The first time this tells me that the values โ€‹โ€‹of the array are undefined. The second time they are available.

Here is the html:

<div class="testBind"></div> <div class="testBind"></div> <div class="testBind"></div> 

And here is js:

 var numbers = [1, 2, 3]; function whichNumber(n){ console.log('n----:' + n); return n; } var testKeyFunction = d3.selectAll("div.testBind").data(numbers, whichNumber); 

When I run this, I get:

 n----:undefined n----:undefined n----:undefined n----:1 n----:2 n----:3 

Here is the violinist: http://jsfiddle.net/5f8mo2sa/3/

The reason this is a problem (except wtf) is because when the data is an array of objects, and I try to reference the key in this function, it throws an undefined error.

+5
source share
1 answer

From d3 help:

You can specify a key function to control the connection of data with elements. This replaces the default behavior; key function is invoked once for each element in the new data array, and once again for each existing element in the selection . In both cases, the key function is passed to datum d and index i. When a key function is evaluated by new data elements, this context is an array of data; when a key function is evaluated against an existing selection, this context is an associated DOM element.

What you see in the first cycle goes through the existing data (which is not), then it goes through a new data array (which has the expected values). If the key function depends on the object, you must first check to make sure that the object exists.

+4
source

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


All Articles