Rm558
Rm558

Reputation: 5002

How to chain a function call in D3?

Defined a draw function in order to reuse, but it's standalone statement.

draw(circles);

Is there a way to put (rewrite) draw function back to D3's function chain?

svg.selectAll("circle")
            .data(dataset)
            .enter()
            .append("circle")
            .draw(???) //not work. 

Here is the code. a working version is here

<body>
    <script type="text/javascript">

        var draw = function (circles) {
            circles.attr("cx", function (d, i) {
                return (i * 50) + 25;
            })
         .attr("cy", h / 2)
         .attr("r", function (d) {
            return d;
         });
        };

        var w = 500, h = 50;

        var dataset = [5, 10, 15, 20, 25];
        var dataset2 = [25, 20, 15, 10, 5];

        var svg = d3.select("body")
                    .append("svg")
                    .attr("width", w)
                    .attr("height", h);

        var circles = svg.selectAll("circle")
            .data(dataset)
            .enter()
            .append("circle")

        draw(circles);

        var circles2 = svg.selectAll("circle")
        .data(dataset2)
        .transition()
        .duration(2000);

        draw(circles2);

    </script>
</body>

Upvotes: 2

Views: 1391

Answers (1)

Rm558
Rm558

Reputation: 5002

Use call() + this in draw(). A working version is here

var draw = function () {
    this.attr("cx", function (d, i) {
        return (i * 50) + 25;
    })
    .attr("cy", h / 2)
    .attr("r", function (d) {
        return d;
    });
};

circles
.data(dataset)
.enter()
.append("circle")
.call(draw)
.data(dataset2)
.transition()
.attr("fill", "red")
.duration(2000)
.call(draw);

Upvotes: 2

Related Questions