Unmounting Mithril.js components

Update 2019-07-05: the issue I opened has been fixed by this PR, thanks Mithril team! It is no longer required that the event listeners (onpopstate, onhashchange) be removed manually. All you have to do is the mounting of null.

I've been using mithril.js in apps for a while now, and have really come to like it. Recently, I came across a situation where I needed to have a mithril application play it nice with another JS framework, and the question was, how do I destroy/unmount a mithril component from the page when exiting or navigating away from the page in another JS framework (in this case Svelte, but could apply with React, or others)? I decided to post this to help save you time. Instead of Googling for a while like I did reading outdated mithril.js guides, just read this. I ended up finding the solution in mithril.js' source (duh). Say you have an app that hands off control to mithril by mounting it like so:

const mountPoint = document.body;
m.route(mountPoint, "/error/404", { /** Routes **/ });

So now your app is mounted and takes over the document body. How do you hand back over control to the other framework? Simple in hindsight:

m.mount(mountPoint, null);

Easy, right? So why does that work? Well in mithril's source here I found that if you pass null (and exactly null, not false or undefined, it's checked with ===) to m.mount, it conveniently blanks out the DOM and unsubscribes the component from the redraw service. Be sure to also remove all your event listeners you made in your mithril code!

UPDATE 2019-06-19: If you're using the mithril router specifically, then it's important you also remove its event listener:

window.onpopstate = null;
Blog Comments powered by Disqus.