javascript - Auto unmount when removed from DOM -
consider following example:
riot.mount('clock') settimeout(()=>{ console.log("removing 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>
where mount tag, remove using normal dom methods. in case, can seen although tag no longer in existence, hasn't been unmounted , therefore disposal code in unmount
event handler not run.
i use dom mutationobserver handle case, wondering if i'm missing something.
check parentnode
on update , call unmount
if doesn't exist.
riot.mount('clock') settimeout(()=>{ console.log("removing 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>
Comments
Post a Comment