5

I know that in jQuery if we use .remove() for removing some element, then all bound events and jQuery data associated with the elements are removed. Is the same true for d3?

If the answer is yes, then if I bind events to nodes in an svg using .on() and then remove the svg using .remove(), are all of the events for all of the nodes on the svg also unbound (i.e. are the events for the children of the svg removed)?

If the answer is no to either of the questions above, I'm assuming I would need to manually unbind elements using .on('eventType',null). I was attempting to write a general purpose function for something like this that would look like:

function unbindCommonEvents(elem){
  var eventTypes = ['click','dblclick','mousedown','mouseup','mouseover','mousemove','mouseout','dragstart','drag','dragenter','dragleave','dragover','drop','dragend','Keyboard','keypress','keyup','load','unload','abort','error','resize','scroll','select','change','submit','reset','focus','blur','focusin','focusout','zoom'];
  for (var i = 0; i < eventTypes.length; i++) {
    elem.on(eventTypes[i],null);
  };
return false;
}

However, this seems cumbersome. There must be a more elegant solution, perhaps something similar to the solutions posted here?

Community
  • 1
  • 1
John Dittmar
  • 161
  • 5
  • 3
    Removing an element should also remove all its event listeners. – Lars Kotthoff Aug 21 '13 at 20:27
  • Well that answers that. Thanks Lars! I was worried orphaned event listeners causing memory leaks but I guess I don't need to anymore. – John Dittmar Aug 22 '13 at 15:27
  • 1
    For a longer answer, see [this question](http://stackoverflow.com/questions/12528049/if-a-dom-element-is-removed-are-its-listeners-also-removed-from-memory). – Lars Kotthoff Aug 22 '13 at 15:40
  • See also http://stackoverflow.com/questions/18382286/d3-js-should-i-detach-event-listener-on-exit-remove – explunit Sep 02 '13 at 15:02

0 Answers0