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

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

本文关键字:删除 处理 程序 选择器 js 何使用 d3      更新时间:2023-11-23

我使用正在更新的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
}

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
}

,运气不佳。

注意:使用d3 v2.9.1,

发现尽管d3 v2.9.1不支持.off(),但有一个替代方案.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 
    });
}

参考:

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