如何使用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 }
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 .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 }); }
参考:
在此处找到此信息: