从DOM中删除时自动卸载

时间:2016-07-06 11:40:24

标签: javascript dom riot.js

考虑以下示例:



riot.mount('clock')
setTimeout(()=>{
  console.log("removing from dom")
  var el = document.getElementsByTagName("clock")[0];
  el.parentNode.removeChild(el);
  riot.update();
}, 5000)

<script src="https://cdnjs.cloudflare.com/ajax/libs/riot/2.5.0/riot+compiler.min.js">
</script>
<script type="riot/tag">
  <clock>
      <p>{ time }</p>
      
      this.time = new Date();
      tick() {
        this.update({ time: new Date() })
      }
      var timer = setInterval(this.tick, 1000)
      this.on("unmount",() => {
      	console.log("unmounted")
        clearInterval(timer)
      });
      this.on("update",() => {
        console.log("on update");
      });
      this.tick();
  </clock>
</script>

<clock></clock>
&#13;
&#13;
&#13;

我们挂载标记,然后使用普通的DOM方法删除它。在这种情况下,可以看出虽然标签不再存在,但它尚未卸载,因此unmount事件处理程序中的处理代码不会运行。

我可以使用DOM MutationObserver来处理这种情况,但我想知道我是否遗漏了某些东西。

1 个答案:

答案 0 :(得分:1)

检查更新时的parentNode,如果不存在,请致电unmount

&#13;
&#13;
riot.mount('clock')
setTimeout(()=>{
  console.log("removing from dom")
  var el = document.getElementsByTagName("clock")[0];
  el.parentNode.removeChild(el);
  riot.update();
}, 5000)
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/riot/2.5.0/riot+compiler.min.js">
</script>
<script>
  riot.mixin("autoUnmount", {
    init: function() {
      this.on("update",() => {
        if (!this.root.parentNode) {
          this.unmount();
        }
      });
    }
  });
</script>
<script type="riot/tag">
  <clock>
      <p>{ time }</p>
      
      this.mixin("autoUnmount");
      this.time = new Date();
      tick() {
        this.update({ time: new Date() })
      }
      var timer = setInterval(this.tick, 1000)
      this.on("unmount",() => {
      	console.log("unmounted")
        clearInterval(timer)
      });
      this.on("update",() => {
        console.log("on update");
      });
      this.tick();
  </clock>
</script>

<clock></clock>
&#13;
&#13;
&#13;