HeyWatchThis
HeyWatchThis

Reputation: 23463

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

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 ,

Upvotes: 35

Views: 21602

Answers (1)

HeyWatchThis
HeyWatchThis

Reputation: 23463

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

Upvotes: 42

Related Questions