How to register multiple external listeners to the same selection in d3?

I'm writing a project in d3 in which I have an html page incorporating two external javascript files, say script_1.js and script_2.js.
I need to register one event listener from script_1.js and another from script_2.js for the change event on a select element. At present I have this line in my html:

<select id="timebasis" class="selector" onchange="selectIndexSp(this),selectIndexBt(this)">

where selectIndexSp(object) and selectIndexBt(object) are defined respectively in script_1.js and script_2.js. I don't like this approach at all, and I'd like to know how to perform the same task in d3 rather than in the html file, which I know isn't a good practice.

Thanks in advance!


Solution 1:

You can add a namespace to the event name like:

d3.select("#timebasis")
    .on("change.sp", listenersp)
    .on("change.bt", listenerbt);

See: https://github.com/mbostock/d3/wiki/Selections#wiki-on

If an event listener was already registered for the same type on the selected element, the existing listener is removed before the new listener is added. To register multiple listeners for the same event type, the type may be followed by an optional namespace, such as "click.foo" and "click.bar". To remove a listener, pass null as the listener.

The functions are being passed the current datum d and index i, with the this context as the current DOM element. It looks like your two function expect the DOM element as argument? In that case it would look like:

d3.select("#timebasis")
    .on("change.sp", function() { selectIndexSp(this); })
    .on("change.bt", function() { selectIndexBt(this); });