Does removing a DOM element with an event listener attached cause a memory leak in dart:html?

StackOverflow https://stackoverflow.com/questions/23416686

  •  13-07-2023
  •  | 
  •  

سؤال

Let's say I have many elements and each has its own listener attached to it like so:

DivElement _container = querySelector("#container");

void _createButtons(int count) {
  for (int i = 0; i < count; i++) {
    var button = new ButtonElement()
    ..text = "Button #$i";
    button.onClick.listen((_) => print("Clicked #$i."));
    _container.append(button);
  }
}

And then at some point I clear the DOM, like so:

_container.clear();

Should I be worried about the 'orphaned' event listeners?

It seems like this is not clear in pure JavaScript (see Does remove a DOM object (in Javascript) will cause Memory leak if it has event attached?, for example). Looking at Chrome DevTools Timeline, it looks like there are listeners kept around, but I'm not sure if that's related to what I'm asking.

I could, of course, keep around the StreamSubscription and cancel it "to be sure", but I don't want to do that if it's not absolutely necessary. It makes the code complex.

هل كانت مفيدة؟

المحلول

The garbage collector will remove the listeners (the same way as JS gets rid of unused listeners). You can safely drop the subscriptions if you don't need them anymore.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top