While continuing on my knockoutjs adventure, we recently had a need to prompt the user when they were leaving the page. A common use case for this is when the user is editing something and navigates away from the page before saving any changes. The navigation can be done by using the back button, a link on the page, or closing the browser or tab. Javascript provides a helpful event, the onbeforeunload
event.
The typical pattern for using this event is as follows:
1 | window.onbeforeunload = confirmExit; |
You set onbeforeunload
to a function that returns a string. The string will show up in a dialog box like this when navigating away:
This has been around for a while. But I wanted to be able to do this in a way that used the MVVM pattern in Knockout. I wanted to have this controlled by data binding between my markup and viewmodel.
So I created the beforeUnloadText
custom binding.
1 | // Author: Tim Larson @codethug |
And here is how you use it (jsFiddle demo)
1 | <body data-bind="beforeUnloadText: beforeUnloadPrompt"> |
1 | var ViewModel = function() { |
The idea is that the user is editing something, and we want to prompt them to save their work before they leave the page. However, once they have saved their work, there is no further need for a prompt, so the prompt is disabled by setting it to null.