Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
434 views
in Technique[技术] by (71.8m points)

javascript - 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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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); });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...