This particular issue involves functions specific to D3, but is not limited to D3. I have developed two D3 charts and implemented zoom functionality on both with the intention of synchronizing the zoom scale and position - so that when one chart is zoomed, the other will automatically adjust to the same scale and spot. To accomplish this, I utilize a custom event trigger when a zoom action is performed on one chart, allowing me to dynamically modify the second chart:
// Inside the chart definition:
var svg = ...; // The chart body definition
var zoom = d3.behavior.zoom()
.on("zoom", function(e){
// carry out necessary actions...
$("#chart-div").trigger({
type: "my.zoom",
translate: d3.event.translate,
scale: d3.event.scale
});
});
svg.call(zoom);
Furthermore, I craft methods enabling manual adjustments to the zoom level of each chart, which in turn triggers the D3 zoom
event:
var adjustZoom = function(t,s){
svg.transition().duration(500).call(zoom.scale(s).translate(t).event);
};
To complete the setup, event listeners are attached to both charts so that changes in the zoom level of one chart lead to automatic updates in the other:
$("#chart-div1").on("my.zoom", function(e){
chart2.adjustZoom(e.translate, e.scale);
});
$("#chart-div2").on("my.zoom", function(e){
chart1.adjustZoom(e.translate, e.scale);
});
The primary challenge arises from invoking the adjustZoom
method triggering the D3 zoom
event, thus creating a loop between the two charts where each tries to adjust the other indefinitely.
1. chart1 [manual zoom] --> trigger d3.zoom --> triggers my.zoom
2. chart2 [my.zoom listener] --> trigger d3.zoom --> triggers my.zoom
3. chart1 [my.zoom listener] --> trigger d3.zoom --> triggers my.zoom
etc...
I am seeking a solution to detect whether the my.zoom
event has been fired already before triggering another my.zoom
event, thereby avoiding the cyclic events (as seen in step 3 above), however, I am uncertain how to achieve this. Is there a way for a function or event to recognize the event that triggered it and halt itself?