【问题标题】:How do you remove a handler using a d3.js selector如何使用 d3.js 选择器删除处理程序
【发布时间】:2013-12-14 16:24:26
【问题描述】:

我不小心使用正在更新的 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 ,

【问题讨论】:

  • 您提到这是在更新期间。您是否考虑过仅在 .enter 选择期间添加事件处理程序?见d3 Lifecycle events
  • 这种情况常见吗? >>:我在上面的 add_listeners() 中添加了十个其他处理程序。其中一些 not 在 d3.js 对象上,.off() 工作。所以我希望在一个地方统一解决这个问题。
  • 事件处理程序在做什么?他们都在同一个选择上吗?可能过度,但一切都取决于上下文。
  • 在上面添加了一些更清晰的内容。

标签: javascript jquery svg d3.js


【解决方案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

【讨论】:

  • 还值得注意的是,official documentation 表示:If an event listener was already registered for the same type on the selected element, the existing listener is removed before the new listener is added.。所以实际上不需要调用.on('click', null),因为旧的事件监听器将被覆盖。
  • 但我认为我们仍然应该这样做以避免内存泄漏..怎么说
猜你喜欢
  • 2012-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多