javascript 如何使用 d3.js 选择器删除处理程序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20269384/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 18:07:46  来源:igfitidea点击:

How do you remove a handler using a d3.js selector

javascriptjquerysvgd3.js

提问by HeyWatchThis

I was accidentally overlaying the same event handler on top of svg elements using d3 selectors I was updating.

我不小心使用我正在更新的 d3 选择器在 svg 元素之上覆盖了相同的事件处理程序。

add_listeners = function() {
    d3.selectAll(".nodes").on("click", function() { 
        //Event handler to highlight clicked d3 element
    });

    jQuery('#some_navigation_button').on('click', function() { 
        //Event handler 
    });
    jQuery('#some_refresh_button').on('click', function() { 
        //Event handler that re-draws some d3 svg elements
    });

    //... 5 other navigation and d3 handlers
}

The add_listeners()was re-adding the same handlers. So I tried

add_listeners()重新添加相同的处理程序。所以我试过了

add_listeners = function() {
    d3.selectAll(".nodes").off();
    jQuery('#some_navigation_button').off();
    jQuery('#some_refresh_button').off();

    d3.selectAll(".nodes").on("click", function() { 
        //Event handler 
    });
    jQuery('#some_navigation_button').on('click', function() { 
        //Event handler 
    });
    jQuery('#some_refresh_button').on('click', function() { 
        //Event handler that re-draws some d3 svg elements
    });

    //... 5 other navigation and d3 handlers
}

, with no luck.

,没有运气。

Notes: using d3 v2.9.1 ,

注意:使用 d3 v2.9.1 ,

回答by HeyWatchThis

Found out that although .off()is not supported for d3 v2.9.1, an alternative is .on('click',null)

发现虽然.off()d3 v2.9.1 不支持,但另一种选择是 .on('click',null)

Fully:

完全:

add_listeners = function() {
    // Remove handler before adding, to avoid superfluous handlers on elements.
    d3.selectAll(".nodes").on('click',null);

    d3.selectAll(".nodes").on("click", function() { 
        //Event handler 
    });
}

Reference:

参考:

https://github.com/d3/d3-selection#selection_on

https://github.com/d3/d3-selection#selection_on