-
Notifications
You must be signed in to change notification settings - Fork 85
chart events
Charts support a basic event API that allows you to trigger events on the chard and bind to/unbind from them.
You can bind to a chart event using the .on
function. The on
function takes three parameters:
- The
name
of the event to bind to - The
callback
to execute - The
context
of the callback. This is an optional parameter.
For example:
var myChart = d3.select("#container")
.append("svg")
.chart("ChartType")
.width(110);
myChart.on("brush", function(d) {
console.log("The element ", d, "was brushed");
});
Note that the on
API that allows custom events is only available on the chart itself, not on layers or any other selections within the chart base.
You can also bind to an event once, by using the once
API call. The signature of once
is identical to the on
function, the only difference being that after being executed once, the callback will be unbound.
To trigger events, you can use the trigger
API on the chart. The trigger
function takes the following parameters:
- The
name
of the event to trigger 2..*. Any number of arguments that will be passed to the callback.
Most of the time, the chart itself will trigger events from within its functions. For example:
d3.chart("Circles").extend("HoverableCircles", {
initialize: function() {
// add a new behavior on the `enter` lifecycle event.
// note that this doesn't overwrite the previous `enter`
// behavior! It just adds additional behavior to it.
this.layer("circles").on("enter", function() {
var chart = this.chart();
// add a mouseover listener to our circles
// and change their color and broadcast a chart
// brush event to any listeners.
this.on("mouseover", function() {
var el = d3.select(this);
el.style("fill", "blue");
chart.trigger("brush", this);
}).on("mouseout", function() {
var el = d3.select(this);
el.style("fill", "red");
})
});
}
});
var myChart = d3.select("#container")
.append("svg")
.chart("HoverableCircles")
.width(110);
myChart.on("brush", function(d) {
console.log("The element ", d, "was brushed");
});
Cleaning up any lingering chart events is incredibly important. You can remove any event listeners by calling off
on the chart. The off
method takes the following arguments:
-
name
- The name of the event to unbind. Optional. -
callback
- The specific callback to unbind. Optional. -
context
- The context for which callbacks should be unbound. Optional.
Calling off
without any arguments will remove all listeners.
Calling off
with just a name will remove all listeners for that event.
Calling off
with any permutation of the three arguments will remove the listeners that match that set of permutations.