Created
February 22, 2012 07:00
-
-
Save grssam/1882705 to your computer and use it in GitHub Desktop.
unload() function
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
/** | |
* Provide a way to remove / undo any changes made | |
* either at the unloading of the script/add-on in which this function is used | |
* or at the unloading of the container, if provided | |
* | |
* @param callback | |
* function to call when unloading of the script or container. | |
* This function should undo all the changes made. | |
* @param container | |
* Optional, the scope of the function. | |
* That is, if the scope is being unloaded, or destroyed | |
* the function would be called | |
* @return removeUnloader | |
* reference to the function, which when called, | |
* prevents the function callback to be called | |
* in case of unloading of script or container | |
*/ | |
function unload(callback, container) { | |
// Initialize the array of unloaders on the first usage | |
let unloaders = unload.unloaders; | |
if (unloaders == null) | |
unloaders = unload.unloaders = []; | |
// Calling with no arguments runs all the unloader callbacks | |
if (callback == null) { | |
unloaders.slice().forEach(function(unloader) unloader()); | |
unloaders.length = 0; | |
return; | |
} | |
// The callback is bound to the lifetime of the container if we have one | |
if (container != null) { | |
// Remove the unloader when the container unloads | |
container.addEventListener("unload", removeUnloader, false); | |
// Wrap the callback to additionally remove the unload listener | |
let origCallback = callback; | |
callback = function() { | |
container.removeEventListener("unload", removeUnloader, false); | |
origCallback(); | |
} | |
} | |
// Wrap the callback in a function that ignores failures | |
function unloader() { | |
try { | |
callback(); | |
} | |
catch(ex) {} | |
} | |
unloaders.push(unloader); | |
// Provide a way to remove the unloader | |
function removeUnloader() { | |
let index = unloaders.indexOf(unloader); | |
if (index != -1) | |
unloaders.splice(index, 1); | |
} | |
return removeUnloader; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment