user603007
user603007

Reputation: 11794

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();

Upvotes: 3

Views: 4824

Answers (3)

Awais Qarni
Awais Qarni

Reputation: 18006

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();
}

Upvotes: 3

saintedlama
saintedlama

Reputation: 6898

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.

Upvotes: 1

katspaugh
katspaugh

Reputation: 17899

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. */ });

Upvotes: 4

Related Questions