Created
June 15, 2024 12:12
-
-
Save barneycarroll/e5bd06fa0ae9abeb6a683eb9a95d5250 to your computer and use it in GitHub Desktop.
A `beforeonunload` emulator for Mithril
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function BeforeUnload(){ | |
const route. = m.route.set | |
const handler = e => { | |
if( | |
e.target.href | |
&& | |
e.target != '_blank' | |
&& | |
!confirm(message) | |
){ | |
// Need to prevent (native behaviour) & stop (Mithril bindings) | |
e.preventDefault() | |
e.stopPropagation() | |
} | |
}, | |
return { | |
view: () => {}, | |
oncreate: ({attrs: {message = 'Are you sure?'}}) => { | |
addEventListener('click', handler, true) | |
m.route.set = function(){ | |
if(confirm(message)) | |
return route.apply(this, arguments) | |
} | |
}, | |
onremove: () => { | |
removeEventListener('click', handler, true) | |
m.route.set = route | |
}, | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment