Michael Johansen
Michael Johansen

Reputation: 5116

D3 zoom callback

Take this timeless example of D3 zoom. Shortened code below:

var svg = d3.select("svg")
  ...;

var zoom = d3.zoom()
    .scaleExtent([1, 40])
    .translateExtent([[-100, -100], [width + 90, height + 100]])
    .on("zoom", zoomed);

...

d3.select("button")
    .on("click", resetted);

svg.call(zoom);

function zoomed() {
  view.attr("transform", d3.event.transform);
  gX.call(xAxis.scale(d3.event.transform.rescaleX(x)));
  gY.call(yAxis.scale(d3.event.transform.rescaleY(y)));
}

function resetted() {
  svg.transition()
      .duration(750)
      .call(zoom.transform, d3.zoomIdentity);
}

In the D3 Zoom library one specifies the zoom behavior, then applies the zoom to the canvas or SVG target. How/where could I send a callback as a param to zoomed() without redefining the zoom behavior?

Upvotes: 2

Views: 1126

Answers (1)

Gerardo Furtado
Gerardo Furtado

Reputation: 102218

Since you asked...

How/where could I send a callback as a param?

... your question is dangerously too broad. But here is a possibility (out of many):

Suppose this simple callback function:

function callback(x){
    console.log(x);
}

We can send it to the zoom function changing the listener. So, instead of:

.on("zoom", zoomed);

We can do:

.on("zoom", function(){
    zoomed(callback)
});

And, in the zoom function, setting the callback argument. For instance, let's log the d3.event.transform:

function zoomed(fn) {
    fn(d3.event.transform);
    //rest of the code...
}

Here is a demo bl.ocks: http://blockbuilder.org/GerardoFurtado/38c77c024ba4cc42c86221117fed4164

Upvotes: 2

Related Questions