如何从外部触发d3事件 [英] How to externally trigger d3 events

查看:115
本文介绍了如何从外部触发d3事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在d3选项上定义了事件回调.

I have a d3 selection upon which I have defined event callbacks.

var obj = d3.select("#kk").on("mouseleave",function(){
              console.log("mouse leave");       
          });

如何从外部触发事件?是否有类似的东西:

How can I trigger the event externally? Is there something like:

obj.mouseleave(); // actuall mouse leave function calling

如果存在,并且如果我没有参考obj来选择对象,则触发器仍将起作用吗?

If there is, and if I select the object without referring to obj, will the trigger still work?

如:

var newObje=d3.select("#kk");
newObje.mouseleave(); //will this trigger the previously defined instructions

推荐答案

如果您已经在D3 v4 上,则可以使用

If you are already on D3 v4, you can use selection.dispatch() which was specifically designed to do exactly what you are looking for:

# 选择 .调度(类型 [,参数])<>

# selection.dispatch(type[, parameters]) <>

调度指定类型自定义事件 em>依次选择每个选定的元素.

Dispatches a custom event of the specified type to each selected element, in order.

由于问题能够手动触发事件处理程序,因此该内容已包含在v4中. #100" .

此外,该方法使您可以将相同类型的事件分派到所选内容中包含的所有元素.该方法的实现与其他应答者通过使用event.dispatch()所采用的方法相似,但将使您的生活更加轻松.以下代码段为每个单独的圈子提供了一个侦听器,该侦听器可以一次由按钮触发.

Furthermore, the method will enable you to dispatch events of the same type to all elements contained in the selection. The implementation of that method looks similar to the approach the other answerers took by putting event.dispatch() to use, but will make your life somewhat easier. The following snippet has a listener for each individual circle, which may all be triggered by the button at once.

var circles = d3.select("svg").selectAll("circle")
  .data(d3.range(5))
  .enter().append("circle")
    .attr("cx", function(d, i) { return 60 * i + 20; })
    .attr("cy", "30")
    .attr("r", "20").attr("fill", "blue")
    .on("mouseleave",function(){
      d3.select(this)
        .attr("fill", "red")
        .transition().duration(1000)
        .attr("fill", "blue");
    });

d3.select("#btn")
  .on("click", function() {
    circles.dispatch("mouseleave");
  });

<script src="https://d3js.org/d3.v4.js"></script>
<svg width="400" height="70"></svg>

<button id="btn">Dispatch mouseleave to all circles</button>

这篇关于如何从外部触发d3事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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