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; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hmm, wasn't able to get this to work
Am I doing something wrong?