gpt4 book ai didi

javascript - 从 DOM 中删除时自动卸载

转载 作者:行者123 更新时间:2023-11-30 00:06:44 25 4
gpt4 key购买 nike

考虑以下示例:

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>

我们在其中安装标签,然后使用普通的 DOM 方法将其删除。在这种情况下,可以看出虽然标签不再存在,但它还没有被卸载,因此 unmount 事件处理程序中的处理代码没有运行。

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

最佳答案

更新时检查 parentNode,如果不存在则调用 unmount

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>
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>

关于javascript - 从 DOM 中删除时自动卸载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38223137/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com