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

2019-04-18 00:44发布

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

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 = 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 ,

1条回答
爷的心禁止访问
2楼-- · 2019-04-18 01:40

Found out that although .off() is not supported for d3 v2.9.1, an alternative is .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

查看更多
登录 后发表回答