2016-11-04 65 views
6

我有一个d3选择,我已经定义了事件回调。如何从外部触发d3事件

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

如何从外部触发事件?有什么样:

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

如果有,如果我选择的对象,而指的是obj,将触发还能用吗?

如:

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

回答

4

如果你已经在D3 V4,您可以使用selection.dispatch()这是专门用来做的正是你在找什么:

#选择派遣 [,参数])<>

指派指定类型到每个所选择的元素的custom event,为了。

由于问题"Ability to trigger event handlers manually. #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"); 
 
    });
<script src="https://d3js.org/d3.v4.js"></script> 
 
<svg width="400" height="70"></svg> 
 

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

+0

这很酷,很棒的除了d3 v4,不知道这个! –

2

你可以让一个常数函数鼠标离开,并把它当鼠标离开或外部,以及这样的:

function mouseleave(){   // Main mouse leave function. 
    console.log('inside mouseleave function.');  
} 



var obj = d3.select("#kk").on("mouseleave",function(){ // It will call on actual mouse leave event 
        console.log("mouseleave"); 
        mouseleave(); 
       }); 

    mouseleave(); // call it externally when ever you want. 
+0

我的应用程序有骨干模型的结构复杂,回调函数实际上是存储在一个嵌套的收集和扳机是由完全不同的一个量身定做的,我不希望让全球功能。 – SachiDangalla

4

以下将触发对mouseleave事件元素通过dispatchEvent()

var event = document.createEvent('Event'); 
    event.initEvent('mouseleave', true, true); 

    d3.selectAll("circle").node().dispatchEvent(event); 

例子:http://codepen.io/anon/pen/eBYvVN(我已经在底部增加了一个按钮来触发它MouseLeave事件被连接到圆)

7

是的,你不需要D3触发事件,香草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); 
 
};
#kk { 
 
    width:100px; 
 
    height:100px; 
 
    background-color:blue; 
 
    }
<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>