javascript 如何使用 d3.js 选择器删除处理程序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20269384/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you remove a handler using a d3.js selector
提问by HeyWatchThis
I was accidentally overlaying the same event handler on top of svg elements using d3 selectors I was updating.
我不小心使用我正在更新的 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
}
The add_listeners()
was re-adding the same handlers. So I tried
将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
}
, with no luck.
,没有运气。
Notes: using d3 v2.9.1 ,
注意:使用 d3 v2.9.1 ,
回答by HeyWatchThis
Found out that although .off()
is not supported for d3 v2.9.1, an alternative is
.on('click',null)
发现虽然.off()
d3 v2.9.1 不支持,但另一种选择是
.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:
参考: