简体   繁体   中英

how to add more functions to window.onunload?

suppose I have some javascript which says:

window.onunload=some_jsfunction();

how can I add another function to this handler? something like this:

window.onunload=some_jsfunction() + another_jsfunction();

The first and foremost way: addEventListener :

window.addEventListener('unload', function () { /* Do things. */ });
window.addEventListener('unload', function () { /* Do other things. */ });

Another way is too create a new event handler with a call to the old handler from it, then overwrite the old handler. I can imagine a situation where it could be useful, but not with DOM events:

var onUnload = function () {
    /* Do things. */
};

var oldOnUnload = onUnload;

onUnload = function () {
    oldOnUnload();
    /* Do new things. */
};

The most advanced way is creating your own observer on top of the DOM's observer (this is what frameworks like Mootools do internally). It can be helpful in the long term; for example, to add event namespaces.

var handlers = [];

window.onunload = function () {
    handlers.forEach(function (fn) { fn(); });
};

handlers.push(function () { /* Do things. */ });
handlers.push(function () { /* Do other things. */ });

Call a function on window.onunload and call your function in that function. Some thing like this

window.onunload = callFunctions;

While your callFunctions look like

function callFunctions() {
  someFunction();
  anotherFunction();
}

The jQuery library uses a approach event listeners for the document ready function are put in a callback list and the functions get called when the ready event is fired. For your problem this could be implemented somehow like this

    onunloadList = new Array();
    function addOnUnloadHandler( fn ) {
      // Add the callback
      onunloadList.push( fn );
    }

    function handleOnUnloadHandlers( fn ) {
      for (i=0;i<onunloadList.length;i++) {
        var fn = onunloadList[i];
        fn();
      }
    }

    window.onunload = handleOnUnloadHandlers();

In general I'd recommend to use some kind of framework like jQuery because that has such mechanism built in. And code you don write you don't have to maintain.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM