Thursday, December 5, 2019

D3 Data binding



Data binding is  binding data to DOM elements and create new elements based on the data provided.

Below are Main methods

data() Joins data to the selected elements
enter() Creates a selection with placeholder references for missing elements
exit() Removes nodes and adds them to the exit selection which can be later removed from the DOM
datum() Injects data to the selected element without computing a join.

Example is below

var myData = ["Hello World!"];
   
         var p = d3.select("body")
                .selectAll("p")
                .data(myData)
                .text(function (d) {
                    return d;
                });


enter() creates placeholder first so that the data can operate on
e.g below


var data = [4, 1, 6, 2, 8, 9];
    var body = d3.select("body")
                .selectAll("span")
                .data(data)
                .enter()
                .append("span")
                .text(function(d) { return d + " "; });

The enter() function checks for elements corresponding to our five array elements. Since it does not find any, it will create a span for each of the five elements.

.append("span")
And this will append above created spans to the body element.

Exit() method

While enter() is used to add new reference nodes, exit is used to remove a node.
In the below code, all p elements will be removed. With exit(), the elements enter an exit phase. This means that all the exited elements are stored in some invisible place ready to be removed when the command is given. And that command is remove(). remove() will remove all the 'exited' nodes from the DOM.

Example: exit() Method

var myData = ["Hello World!"];

    var p = d3.select("body")
                .selectAll("p")
                .data(myData)
                .text(function (d, i) {
                    return d;
                })
                .exit()
                .remove();

datum() method

The datum() function is used for static visualization which does not need updates. It binds data directly to an element.
d3.select("body")
        .select("p")
        .datum(100)
        .text(function (d, i) {
            return d;
        });



References:
https://www.tutorialsteacher.com/d3js/data-binding-in-d3js

No comments:

Post a Comment