删除事件监听器,d3js无法正常工作 [英] Remove event listener with d3js not working

查看:430
本文介绍了删除事件监听器,d3js无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个svg结构,里面有一些形状。我想在单击一个形状时触发一个事件,而在单击一个svg时触发另一个。问题是SVG事件总是被触发。

I have an svg structure where there are some shapes inside. I want to fire an event when a shape is clicked and another one when is clicked over the svg. The problem is the SVG event is always fired.

为了防止这种情况,我禁止事件从形状冒泡。此外,我试图用d3禁用该事件,但似乎无法正常工作。还尝试使用本机javascript代码禁用事件。

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. Also tried to disable event with the native javascript code.

超级简单代码的一个示例是:

An example of the super simple code is:

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代码

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

我知道事件没有被禁用,因为我收到了来自的console.log()文本警报clickEvents函数。

I know event is not being disabled because I'm getting the console.log() text alert from clickEvents function.

谢谢。

推荐答案

在这种情况下,语法:

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

在d3.js中不起作用相反,你应该使用类似的东西:

does not work in 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");
        });
});

这篇关于删除事件监听器,d3js无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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