简体   繁体   English

删除事件监听器,d3js无法正常工作

[英]Remove event listener with d3js not working

I have an svg structure where there are some shapes inside. 我有一个svg结构,里面有一些形状。 I want to fire an event when a shape is clicked and another one when is clicked over the svg. 我想在单击一个形状时触发一个事件,而在单击一个svg时触发另一个。 The problem is the SVG event is always fired. 问题在于SVG事件始终被触发。

In order to prevent this I'm disabling event bubbling from the shape. 为了防止这种情况,我从形状中禁用事件冒泡。 Also I've tried to disable the event with d3 but seems to not work. 我也尝试用d3禁用该事件,但似乎不起作用。 Also tried to disable event with the native javascript code. 还尝试使用本机javascript代码禁用事件。

An example of the super simple code is: 超简单代码的一个例子是:

svg structure svg结构

<svg id="canvas" xmlns="http://www.w3.org/2000/svg" version="1.1">
    <g>
        <circle class="shape" r="10" cx="10" cy="10">
    </g>
</svg>

javascript code javascript代码

d3.select('#canvas').on('click',svgClickEvents);

d3.selectAll('.item')
    .on("mouseover",mouseoverItem)
    .on('mouseleave',mouseleaveItem);

//click
d3.selectAll('.item',function(){

    //when an item is clicked, svgClickEvents must not be fired   
    d3.select('#canvas').on('click',null);  //this should remove the event listener
    //also tried with getElementById('canvas').removeEventListener('click',clickEvents,false);

d3.select(this)
        .on("click",function() {
            d3.event.stopPropagation(); 
            console.log("click circle")
        });
});

I know event is not being disabled because I'm getting the console.log() text alert from clickEvents function. 我知道事件没有被禁用,因为我正在从clickEvents函数获取console.log()文本警报。

Thanks. 谢谢。

In this case, the syntax: 在这种情况下,语法:

d3.selectAll('.classname', function() { ... });

does not work in d3.js. 在d3.js中不起作用 Instead you should use something like: 相反,你应该使用类似的东西:

d3.selectAll('.classname').each(function() { ... });

So in your code above, this should work: 所以在上面的代码中,这应该工作:

d3.selectAll('.item')
  .each(function(){

    //when an item is clicked, svgClickEvents must not be fired   
    d3.select('#canvas').on('click', null);  //this should remove the event listener

    d3.select(this).on("click",function() {
            d3.event.stopPropagation(); 
            console.log("click circle");
        });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM