Last active
December 11, 2015 20:48
-
-
Save codethug/4657291 to your computer and use it in GitHub Desktop.
A custom binding for KnockoutJS allowing you hook into the onbeforeunload event on the window. This will allow you to display a message to the user when navigating away from or closing the page, reminding the user to save their work, etc.
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
// Author: Tim Larson @codethug | |
ko.bindingHandlers.beforeUnloadText = { | |
init: function(element, valueAccessor, allBindingsAccessor, viewModel) { | |
if (window.onbeforeunload == null) { | |
window.onbeforeunload = function(){ | |
var value = valueAccessor(); | |
var promptText = ko.utils.unwrapObservable(value); | |
if (typeof promptText == "undefined" || promptText == null) { | |
// Return nothing. This will cause the prompt not to appear | |
} else { | |
if (promptText != null && typeof promptText != "string") { | |
var err = "Error: beforeUnloadText binding must be " + | |
"against a string or string observable. " + | |
"Binding was done against a " + typeof promptText; | |
console.log(err); | |
console.log(promptText); | |
// By returning the error string, it will display in the | |
// onbeforeunload dialog box to the user. We could throw an | |
// exception here, but the page would unload and the | |
// exception would be lost. | |
return err; | |
} | |
return promptText; | |
} | |
}; | |
} else { | |
var err = "onbeforeupload has already been set"; | |
throw new Error(err); | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
http://codethug.com/2013/02/01/knockout-binding-for-onbeforeunload/