Created
September 11, 2013 20:32
-
-
Save jbourassa/6529382 to your computer and use it in GitHub Desktop.
`window.onbeforeunload` with TurboLinks support.
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
var Unloader = (function() { | |
var handlers = []; | |
var runNative = function() { | |
return findMessage(); | |
}; | |
var findMessage = function() { | |
var message; | |
for(var i = 0; i < handlers.length; i++) { | |
message = handlers[i](); | |
if(message) break; | |
} | |
return message; | |
}; | |
var runTurboLinks = function(e) { | |
var message = findMessage(), | |
confirmResult; | |
if(message) { | |
confirmResult = confirm(message); | |
if(confirmResult) { | |
handlers = []; | |
} | |
return confirmResult; | |
} | |
else { | |
handlers = []; | |
return true; | |
} | |
}; | |
var clearOnce = function() { | |
once = []; | |
}; | |
var Unloader = { | |
init: function() { | |
window.onbeforeunload = runNative; | |
$(window).on('page:before-change', runTurboLinks); | |
}, | |
register: function(fn) { | |
handlers.push(fn); | |
}, | |
unregister: function(fn) { | |
for(var i = 0; i < handlers.length; i++) { | |
if(handlers[i] == fn) { | |
handlers.splice(i, 1); | |
} | |
} | |
} | |
}; | |
return Unloader; | |
})(); |
Hmm, wasn't able to get this to work
$('form[data-check-form]').each ->
$this = $(this)
form_clean = $this.serialize()
Unloader.register -> "Not clean" if $this.serialize() != form_clean
Am I doing something wrong?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This looks nice. So to use it, you'd start with
Doesn't IE8 need some special handling, with setting e.returnValue? http://stackoverflow.com/questions/1119289/how-to-show-the-are-you-sure-you-want-to-navigate-away-from-this-page-when-ch