如何从外部触发d3事件

Sac*_*lla 7 javascript d3.js

我有一个d3选择,我已经定义了事件回调.

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

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

obj.mouseleave(); // actuall mouse leave function calling
Run Code Online (Sandbox Code Playgroud)

如果有,如果我在没有参考的情况下选择对象obj,触发器是否仍然有效?

如:

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

alt*_*lus 8

如果您已经使用D3 v4,那么您可以使用selection.dispatch()专门设计用于完成您正在寻找的内容:

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

按顺序将指定类型自定义事件调度到每个选定元素.

由于问题"能够手动触发事件处理程序.#100",这包含在v4中.

此外,该方法还允许您将相同类型的事件分派给选择中包含的所有元素.该方法的实现看起来类似于其他回答者event.dispatch()使用的方法,但会使您的生活更轻松.以下代码段为每个单独的圆圈都有一个监听器,这些监听器可以全部由按钮一次触发.

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");
  });
Run Code Online (Sandbox Code Playgroud)
<script src="https://d3js.org/d3.v4.js"></script>
<svg width="400" height="70"></svg>

<button id="btn">Dispatch mouseleave to all circles</button>
Run Code Online (Sandbox Code Playgroud)


Hug*_*ron 7

是的,你不需要d3来触发事件,vanilla javascript就足够了.您只需要使用该dispatchEvent功能.

以下是您将如何操作的示例(例如,从按钮).

我添加了d3.select方式和简单的JS方式,两者都应该正常工作.

d3.select("#kk").on("mouseleave",function(){
  console.log("mouseleave");
});

var button = document.getElementById('trigger-event');
button.onclick = function() {
  var evt = new MouseEvent("mouseleave");
  
  // The way to dispatch the event using d3
  d3.select('#kk').node().dispatchEvent(evt);
  
  // The way to dispatch it with plain JS
  document.getElementById('kk').dispatchEvent(evt);
};
Run Code Online (Sandbox Code Playgroud)
#kk {
  width:100px;
  height:100px;
  background-color:blue;
  }
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<div id="kk">
  
</div>


<button id="trigger-event">trigger event</button>
Run Code Online (Sandbox Code Playgroud)