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

Hey*_*his 24 javascript jquery svg d3.js

我使用我正在更新的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
}
Run Code Online (Sandbox Code Playgroud)

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
}
Run Code Online (Sandbox Code Playgroud)

,没有运气.

注意:使用d3 v2.9.1,

Hey*_*his 31

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

全:

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 
    });
}
Run Code Online (Sandbox Code Playgroud)

参考:

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

  • 值得注意的是,[官方文档](https://github.com/mbostock/d3/wiki/Selections#wiki-on)说:`如果事件监听器已在所选元素上注册了相同类型,在添加新侦听器之前删除现有侦听器.所以实际上没有必要调用`.on('click',null)`因为旧的事件监听器将被覆盖. (17认同)