【问题标题】:When I add a stream subscription on a DOM element, and then remove the element later, will dart:html take care of the subscription, too?当我在 DOM 元素上添加流订阅,然后稍后删除该元素时,dart:html 也会处理订阅吗?
【发布时间】:2013-11-21 11:15:52
【问题描述】:

通常,我会创建一个需要监听(鼠标)事件的元素。然后,稍后,我不再需要该按钮,因此我将其删除。像这样:

var button = new ButtonElement()
  ..onClick.listen((_) => print("Clicked!"));

// ... somewhere else in the code or in the callback above
button.remove();

我还应该处理onClick 订阅(以防止内存泄漏)还是为我处理?

【问题讨论】:

    标签: dart


    【解决方案1】:

    我怀疑这不会通过从 DOM 中删除元素来自动完成,因为您可能会在另一点重新插入它。 remove() 的源代码相当简单:

    Node remove() {
      // TODO(jmesserly): is parent == null an error?
      if (parentNode != null) {
        parentNode.nodes.remove(this);
      }
      return this;
    }
    

    但是,如果没有其他对该对象的引用并且元素类被垃圾收集器清理,那么我希望订阅会随之而来(尽管我不知道如何从来源!)。

    【讨论】:

    • 如果元素没有被不能被垃圾回收的变量引用,则订阅被释放和收集。
    猜你喜欢
    • 1970-01-01
    • 2021-01-20
    • 2016-07-27
    • 2015-02-17
    • 2011-09-16
    • 2017-05-06
    • 1970-01-01
    • 2022-01-01
    • 1970-01-01
    相关资源
    最近更新 更多