Skip to content

Removal of mithril event listeners when navigating away from a mithril app #2437

@chocolatkey

Description

@chocolatkey

Mithril Version: v2.0.0-rc.6

(as mentioned on gitter)
I am currently in a situation where a mithril app (using m.route) is being integrated into a site using another JS framework (svelte). I found there was no official way of "destroying" mithril when navigation back in to the other framework occurs, but after looking in the source, I found you can do m.mount(mountPoint, null); which is cool. I properly removed all my event listeners, and all was going well, but today I noticed that m.route assigns listeners to window.onpopstate and window.onhashchange, so I had to also include

window.onpopstate = window.onhashchange = null;

otherwise the event listeners remain and interfere with the routing of the other JS framework. Could a more elegant way of doing this maybe be integrated into mithril, or mentioned in the documentation? My final "destroy" code looks like this:

destroy() {
    // other stuff...
    m.mount(mountingPoint, null);
    window.onpopstate =  window.onhashchange = null; // Removes mithril's router listeners
}

Metadata

Metadata

Assignees

Labels

Type: BugFor bugs and any other unexpected breakage

Type

No type

Projects

Status

Closed

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions