D3.js dispatch custom event with parameter

Posted on September 12, 2017 in
2 min read

This post just to remember me how something apparently easy might turn out so damn time consumer.

My goal: dispatch a custom event from a selection passing a custom parameter.

Let's assume you have a selection:

var circles = d3.selectAll('circle')

And you want to listen for a custom event:

circles.on('myevt', function(d, i){
  console.log('myevt')
})

Now you want to dispatch that custom event, therefore, all the elements listening for it will be notified:

d3.selectAll('circle').dispatch('myevt')

The console.log will print myevt as expected.

Now the quest: how to pass a custom parameter?

First, you have to learn how to catch the event parameter:

circles.on('myevt', function(d, i){
  var evt = d3.event
})

This will get you the event object with its standards properties.

Then, you need to learn how to properly set the parameter in the dispatch function:

d3.selectAll('circle').dispatch('myevt', {detail: {myCustomObject:'bla bla bla'} })

Please note that detail is not there by chance.
It's the required field that can be populated with your custom object, therefore you can access to it with:

circles.on('myevt', function(d, i){
  var myParams = d3.event.detail
})

Fiuu… another little detail learned today.

Here the working snippet if you're interested.