如何向d3中的同一选择注册多个外部侦听器? [英] How to register multiple external listeners to the same selection in d3?

查看:149
本文介绍了如何向d3中的同一选择注册多个外部侦听器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在d3中编写一个项目,其中有一个html页面,其中包含两个外部JavaScript文件,例如 script_1.js script_2.js

我需要从script_1.js注册一个事件监听器,而从script_2.js注册一个事件监听器用于select元素上的change事件。
目前我在我的html中有这一行:

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)">

其中 selectIndexSp(object) selectIndexBt / strong>分别在script_1.js和script_2.js中定义。我不喜欢这种方法,我想知道如何在d3而不是在html文件中执行相同的任务,我知道这不是一个好的做法。

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.

提前感谢!

推荐答案

您可以向事件名称添加命名空间,如:

You can add a namespace to the event name like:

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

请参阅: https://github.com/mbostock/d3/wiki/Selections#wiki-on


如果事件侦听器已在
selected元素上为相同类型注册,则在添加新的
侦听器之前删除现有侦听器。要为同一事件
类型注册多个侦听器,该类型后面可以跟一个可选的命名空间,例如
click.foo和click.bar。要移除侦听器,请传递null作为
侦听器。

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.

函数正在传递当前数据 d 和索引 i ,将 this 上下文作为当前DOM元素。看起来你的两个函数期望DOM元素作为参数?在这种情况下,它看起来像:

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

这篇关于如何向d3中的同一选择注册多个外部侦听器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆