Introduction
KeyLines lets you respond to virtually any event on the chart or time bar elements.
To attach a handler function to an event, you can use the chart.on() and timebar.on() methods. To detach them, use chart.off() and timebar.off().
For a list of events, see the Chart Events API Reference and Time Bar Events API Reference. You can also try them out in our Interaction Events and and Time Bar Events demos.
For details about using events when integrating KeyLines with Leaflet, see the Events section of the Leaflet Integration documentation. To integrate events with frameworks, see the Frameworks demos.
Handling events
To add an event handler,
create an event handler function for the event
and attach it using the on()
function.
When an event fires, any attached handler functions are passed a single object containing all the event details. You can use destructuring to find the properties you want:
function clickHandler({ id, button }) { // we only need the button and item id
// the user clicked the left mouse button or tapped on screen
if (button === 0) {
console.log(id);
}
}
chart.on('click', clickHandler);
To detach the event handler,
use the off()
function and
specify which handler and/or event should be detached.
chart.off('click', clickHandler);
If no handler is supplied, all handlers for the specified event are detached. If no event name is supplied, all event handlers for all events are detached.
Overriding default actions
Some KeyLines events come with default behaviours. For example, dragging a node will move it, clicking on a link will select it, or double-clicking the chart background will zoom in.
To prevent default behaviour,
call the preventDefault()
function in the handler:
// prevent link selection on 'click'
chart.on('click', ({ id, preventDefault }) => {
const chartItem = chart.getItem(id); // get the clicked item
if (chartItem && chartItem.type === 'link') {
// if the item was a link
preventDefault(); // prevent default behaviour
}
});
KeyLines events come with useful event details that capture the context including which button or keyboard key was pressed or which pointing device was used. You can use this information and the setDragOptions function to customise the behaviour.
// if control key is held down when a drag starts, pan the chart
chart.on('drag-start', ({ modifierKeys, setDragOptions }) => {
if (modifierKeys.ctrl) {
setDragOptions({ type: 'pan' });
}
});